I tried to port some of the Yojson functionalities - in particular the Yojson.Basic.Util module - in Elm.
This library provides dynamic json access and manipulation without the need to write decoders.
Elm has a great json library and ecosystem, but in certain situations, in an elm-repl session for example, I'd like to have a more flexible interface. This library, anyway, was written to learn and explore Elm and the use case is more scholastic than practical. It's not meant to replace any of the standard library.
Say we have a json like the following:
rawJson : String
rawJson =
"""
{ "squadName": "Super hero squad"
, "homeTown": "Metro City"
, "formed": 2016
, "secretBase": "Super tower"
, "active": true
, "members":
[
{ "name": "Molecule Man"
, "age": 29
, "secretIdentity": "Dan Jukes"
, "powers":
[ "Radiation resistance"
, "Turning tiny"
, "Radiation blast"
]
}
,
{ "name": "Madame Uppercut"
, "age": 39
, "secretIdentity": "Jane Wilson"
, "powers":
[ "Million tonne punch"
, "Damage resistance"
, "Superhuman reflexes"
]
}
,
{ "name": "Eternal Flame"
, "age": 1000000
, "secretIdentity": "Unknown"
, "powers":
[ "Immortality"
, "Heat Immunity"
, "Inferno"
, "Teleportation"
, "Interdimensional travel"
]
}
]
}
"""if we want to a list of powers, with standard library the code may look like this
powersDecoder : Json.Decode.Decoder (List (List String))
powersDecoder =
Json.Decode.string
|> Json.Decode.list
|> Json.Decode.field "powers"
|> Json.Decode.list
|> Json.Decode.field "members"
powers : List String
powers =
rawJson
|> Json.Decode.decodeString powersDecoder
|> Result.withDefault []
|> List.concatwhile with Yajson we could write
powers_ : List String
powers_ =
rawJson
|> Yajson.fromString
|> Result.withDefault Yajson.Null
|> Yajson.member "members"
|> Maybe.map Yajson.toList
|> Maybe.withDefault []
|> Yajson.filterMember "powers"
|> Yajson.flatten
|> Yajson.filterStringFor more usage examples look here.