Decode JSON with mochijson2 in Erlang

后端 未结 5 916
灰色年华
灰色年华 2021-02-10 07:28

I have a var that has some JSON data:

A = <<\"{\\\"job\\\": {\\\"id\\\": \\\"1\\\"}}\">>. 

Using mochijson2, I decode the data:

5条回答
  •  鱼传尺愫
    2021-02-10 07:59

    My favourite way of handeling mochijson data is replacing all the struct's with hash maps after which they can be cleanly pattern matched. To do so I wrote this easy to understand function:

    structs_to_maps({struct, Props}) when is_list(Props) ->
        lists:foldl(
            fun({Key, Val}, Map) ->
                Map#{Key => structs_to_maps(Val)}
            end,
            #{},
            Props
        );
    structs_to_maps(Vals) when is_list(Vals) ->
        lists:map(
            fun(Val) ->
                structs_to_maps(Val)
            end,
            Vals
        );
    structs_to_maps(Val) ->
        Val.
    

    Here is an example of how to use it:

    do() ->
        A = <<"{\"job\": {\"id\": \"1\"}}">>,
        Data = structs_to_maps(mochijson2:decode(A)),
        #{<<"job">> := #{<<"id">> := Id}} = Data,
        Id.
    

    This has many advantages especially when working with incoming data that can have an unexpected shape.

提交回复
热议问题