Working with Data

Data in Elm is modeled using basic, types, ADTs, Records and data structures, this is similar to any other functional language. The data stored in in all these types often needs to be serialized into other formats. The most common format today is JSON.

Elm provides you with the basic tooling and patterns to serialize and deserialize your Elm types into JSON structures.

Here is a simple example of deserializing a JSON string to an Elm record.

import Graphics.Element exposing (..)
import Json.Decode as Json exposing ((:=))

type alias Point = { x: Float, y: Float, z: Float}

pointJsonString = "{\"x\": 1.414, \"y\": 2.732, \"z\": 1.732 }"

pointDecoder = Json.object3 
  Point 
   ("x" := Json.float) 
   ("y" := Json.float) 
   ("z" := Json.float)

point1 = Json.decodeString pointDecoder pointJsonString

type alias Person = {id : Int, fname : String, lname : String}

personDecoder : Json.Decoder Person
personDecoder =
    Json.object3 Person
      ("id" := Json.int)
      ("fname" := Json.string)
      ("lname" := Json.string)

personJsonString = "{\"id\": 17178, \"fname\": \"John\", \"lname\": \"Smith\"}"

person1 = Json.decodeString personDecoder personJsonString

main =
  flow down [
              print "decode JSON : " point1
              ,print "decode JSON : " person1
            ]
--a helper function to make display easier
print message value = show (message ++ (toString value))

results matching ""

    No results matching ""