3

Would ayone know how to convert

tt :: (Int, [(Int, String)])
tt = (777, [(1, "AA") , (2, "BB") , (3, "CC")])

to JSON similar to

{
"user": 777,
"data": [ 
            { "num": 1 , "typ": "AA" },
            { "num": 2 , "typ": "BB" },
            { "num": 3 , "typ": "CC" } 
        ]
}

using (preferably) Aeson ?

Damir Sudarevic
  • 21,891
  • 3
  • 47
  • 71
  • 7
    Yes, I do. That doesn't mean I'm going to just give you a solution. What have you attempted? – bheklilr Jun 17 '14 at 15:59
  • 3
    The [docs on `ToJSON`](http://hackage.haskell.org/package/aeson-0.7.0.6/docs/Data-Aeson.html#t:ToJSON) will be helpful to you. – Nikita Volkov Jun 17 '14 at 16:01
  • 2
    It would be more idiomatic(the consensus seems to be easier to maintain/reason about too) to use some datatypes rather then nested tuples. It also looks like it would simplify the conversion to json. – Davorak Jun 17 '14 at 18:41

1 Answers1

6

Aeson's toJSON function should convert tt as is, but it won't give you field names. To get names create a custom datatype (and probably a datatype equivalent to (Int,String), to put names on those fields) and derive your own custom instance of ToJSON as described in the docs. For what you want to do you'll probably be able to get away with just deriving Generic and declaring an instance of ToJSON.

Edit: Just tried this and it works fine, but if you really need that data field to be named data you'll have to write a custom toJSON instance because data is a reserved keyword in Haskell and you can't use it as a name for anything.

Leif Grele
  • 223
  • 1
  • 5