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.
Last Post!
NobbZ
You can’t decide it, because you encode it wrong, that’s what I am trying to tell you the whole time.
Have you tried my suggestions from Decoding Multi Level Json - #6 by NobbZ?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









