[Haskell-beginners] Reading JSON using Text.JSON

Adrien Haxaire adrien at adrienhaxaire.org
Sun May 15 21:51:28 CEST 2011


Hello,

I have this JSON string that I have put in a text file, test.json:

{"coordinates": [0.0, 1.0]}

using GHCi, I can read it like this:

 > s <- readFile "test.json"
 > let r = decode s :: Result JSValue
 > r
Ok (JSObject (JSONObject {fromJSObject = [("coordinates",JSArray 
[JSRational False (0 % 1),JSRational False (1 % 1)])]}))

I want to affect this array of two Double to the type Coordinates being 
defined like this:

type Coordinates = (Double, Double)

Using this type I can create a Node:

data Node = Node Coordinates Number
           deriving (Eq, Ord, Show)

The problem is that I have no idea what to do with decoded JSValue. It 
seems I have to define an instance of JSON to read it. Does this mean 
using pattern matching to extract the values ?

What do I do with the Result type ? Should I get rid of it like this:

fromResult :: Result JSValue -> JSValue
fromResult (Ok js) = js
fromResult _ = JSNull

and work with the raw JValue ?

These questions might be trivial, but I know only imperative languages, 
which is why I like so much to learn Haskell and functional programming, 
lots to learn and discover :)

Many thanks in advance,
Adrien



More information about the Beginners mailing list