[Haskell-cafe] Haskell, successing crossplatform API standart

Richard O'Keefe ok at cs.otago.ac.nz
Thu Dec 18 19:18:21 EST 2008


On 18 Dec 2008, at 7:41 pm, Belka wrote:
> Oh, but JSON doesn't seem to support tree-structured data...

Sure it does.  In Haskell terms,

data JSON
    = JSON_Number Double   -- not entirely clear, actually
    | JSON_String String   -- Unicode
    | JSON_Array  [JSON]   -- order matters
    | JSON_Object [(String,JSON)]  -- Unicode keys, order no matter

It supports trees well enough that encoding XML as JSON is trivial.
To a first approximation,

data XML
    = XML_CData String
    | XML_Element String [(String,String)] [XML]

So,

xml_to_json (XML_CData s) =
     JSON_String s
xml_to_json (XML_Elment name atts children) =
     JSON_Object [("n", JSON_String name),
                  ("a", JSON_Object [(k,JSON_STRING v) | (k,v) <-  
atts]),
                  ("c", JSON_Array (map xml_to_json children))]

One can handle the other aspects of XML, I just couldn't be bothered.
Converting JSON that represents XML to XML is straightforward.

Of course the converse is true too.

json_to_xml (JSON_Number x) =
     XML_Element "n" [] XML_CData (show x)
json_to_xml (JSON_String s) =
     XML_Element "s" [] XML_CData s
json_to_xml (JSON_Array  a) =
     XML_Element "a" [] map json_to_xml a
json_to_xml (JSON_Object o) =
     XML_Element "o" []
       [XML_Element "e" [("k",k)] (json_to_xml v) | (k,v) <- o]

Again, converting XML that represents JSON to JSON is straightward,
I just don't need to show it to make the point.
Also obviously, you might as well use Lisp s-expressions.

If you have a choice between XML and JSON, it may be worth remembering
that JSON is *far* easier to parse.  I would expect a JSON parser to
be faster, and more importantly, I would expect it to be more reliable.




More information about the Haskell-Cafe mailing list