I have a var that has some JSON data:
A = <<\"{\\\"job\\\": {\\\"id\\\": \\\"1\\\"}}\">>.
Using mochijson2, I decode the data:
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.