tushar
Decoding Multi Level Json
Below is the json I get after encoding it using Jason
"{\"topic\": \"dummy_topic\", \"msg\": \"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}\"}"
I am trying to pass it as the body of the request while calling an API using HTTPoison , it gives me the json decode error
tried the same on terminal and I get below ,
iex(10)> var = "{\"topic\": \"dummy_topic\", \"msg\": \"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}\"}"
"{\"topic\": \"dummy_topic\", \"msg\": \"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}\"}"
iex(11)> Jason.decode(var)
{:error,
%Jason.DecodeError{
data: "{\"topic\": \"dummy_topic\", \"msg\": \"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}\"}",
position: 35,
token: nil
}}
Which is the exact same error I get when when I use HTTPoison ,
my expectation is I should be getting something like below when I use Jason.decode ,
%{
"topic" => "dummy_topic",
"msg" => %{"fruit" => "apple", "dish" => "apple-pie"}
}
Do you know where I am getting it wrong or what can be done to get the expected output ?
Most Liked
NobbZ
"{\"topic\": \"dummy_topic\", \"msg\": \"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}\"}"
^^
That is where the error is, this matches exactly with what I said, the quotes aren’t escaped properly. The following should be valid:
~S'{"topic": "dummy_topic","msg":"{\"fruit\":\"apple\",\"dish\":\"apple-pie\"}"}'
Alternatively, you have to double escape in the msg field:
"{\"topic\": \"dummy_topic\", \"msg\": \"{\\\"fruit\\\":\\\"apple\\\",\\\"dish\\\":\\\"apple-pie\\\"}\"}"
I prefer the sigil approach for readability.
NobbZ
Due to the doublequotes in the value of msg beeing improperly escaped, you don’t have valid JSON.
NobbZ
Jason.encode(%{
topic: "dummy",
msg: Jason.encode(%{a: "message blob"})
})
# or
~s'{"topic":"dummy","msg":#{Jason.encode(Jason.encode(%{a: "message blob"}))}}'
These variants should both work. I’m not sure about exact quoting here, so it might be, that you need to wrap the interpolated value in another pair of quotes.
I prefer the first approach for readability.







