Chapter 5. Writing a Library: Working with JSON Data

A Whirlwind Tour of JSON

In this chapter, we’ll develop a small, but complete, Haskell library. Our library will manipulate and serialize data in a popular form known as JSON (JavaScript Object Notation).

The JSON language is a small, simple representation for storing and transmitting structured data—for example—over a network connection. It is most commonly used to transfer data from a web service to a browser-based JavaScript application. The JSON format is described at http://www.json.org/, and in greater detail by RFC 4627.

JSON supports four basic types of values—strings, numbers, Booleans, and a special value named null:

"a string" 12345 true
      null

The language provides two compound types: an array is an ordered sequence of values, and an object is an unordered collection of name/value pairs. The names in an object are always strings; the values in an object or array can be of any type:

[-3.14, true, null, "a string"]
      {"numbers": [1,2,3,4,5], "useful": false}

Representing JSON Data in Haskell

To work with JSON data in Haskell, we use an algebraic data type to represent the range of possible JSON types:

-- file: ch05/SimpleJSON.hs
data JValue = JString String
            | JNumber Double
            | JBool Bool
            | JNull
            | JObject [(String, JValue)]
            | JArray [JValue]
              deriving (Eq, Ord, Show)

For each JSON type, we supply a distinct value constructor. Some of these constructors have parameters: if we want to construct a JSON string, we must provide a String ...

Get Real World Haskell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.