So in my previous post on this topic, I ran through how to extract data from a JSON string using Elm if you were just dealing with a simple structure where all the values were of the same type. This example looks at a slightly more complex structure where we're dealing with values of varying types.
module IntermediateJsonParsing where import Dict exposing (Dict) import Html exposing (Html) import Json.Decode exposing ((:=), bool, Decoder, decodeString, float, int, list, object5, string) type alias IntermediateItem = { aFloat : Float , aString : String , anInteger : Int , aBoolean : Bool , aListOfIntegers : List Int } -- An intermediate map of strings to things intermediateJson : String intermediateJson = """{ "aFloat" : -1.010101, "aString" : "Some sort of text", "anInteger" : 12, "aBoolean" : true, "aListOfIntegers" : [1,2,3,2,1] }""" -- the objectX functions allow more complex objects (of up to 8 keys) -- to be extracted. The := function is a shortcut for defining the -- type of each key. intermediateDecoder : Decoder IntermediateItem intermediateDecoder = object5 IntermediateItem ("aFloat" := float) ("aString" := string) ("anInteger" := int) ("aBoolean" := bool) ("aListOfIntegers" := list int) -- A simple function that tries to decode a JSON string with a -- decoder of our choice parseJson : String -> Decoder IntermediateItem -> String parseJson jsonString decoder = case decodeString decoder jsonString of Ok val -> toString val Err err -> err -- Display the result main : Html main = Html.div [] [ Html.text (parseJson intermediateJson intermediateDecoder) ]