Decoding JSON with unique keys


#1

What is the best way to decode a JSON where each key is of a different value? Here is an example:

{
    "location": "NYC",
    "temperatures": {
        "2012-11-01": {"high": "10", "low": "9"},
        "2012-11-02": {"high": "15", "low": "10"}
        ...
    }
}

The tricky part here is that temperatures has its keys as the date. I couldn’t find a decoder in bs-json that could handle this. I am guessing I’ll have to go lower level into Js.Json in order to parse it?


#2

Hi @leolimasa. You are correct in your assumption that you’ll have to go slightly lower level. However you can still leverage bs-json to help with that. Here is some code which might help you get started

let tempSeriesDecoder = json => 
    Js.Json.decodeObject(Js.Json.parseExn(json)) 
    |. Belt.Option.getExn 
    |. Js.Dict.entries 
    |. Belt.Array.map(((k, v))=> (k, decodeTemp(v)));

decodeTemp could just be a normal bs-json decoder for example.


#4

Perfect, thank you @ncthbrt!


#5

Why not leave it? Language is young and this can help a lot of people!