tushar

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

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

NobbZ

Due to the doublequotes in the value of msg beeing improperly escaped, you don’t have valid JSON.

NobbZ

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.

NobbZ

NobbZ

I thought you want msg to be a string containing JSON? Then of course you can not remove the wrapping quotes that make it a string.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement