MetaStack
MetaStack

Reputation: 3716

elixir Poison data type parse Json data

I'm new to elixir, so sorry, I'm sure this is simple.

I can find anything about a data type that follows this pattern:

%{"quoted_string" => "string_w_quotes"}

What is that called?

Here's the problem I'm having. I'm using HTTPoison and Poison. I call a Get request and successfully get a JSON response, then I pipe that whole response to Poison. Then I pattern match on what potion gives me. I'm trying to get to the point where I can say body.address but I get an error.

Here's the relevant code:

# after call
...
body
|> Poison.decode!
|> case do
  {:ok, %HTTPoison.Response{body: body}} ->
    IO.puts "response received"
    body.address
...

Then it prints this:

... response received ** (KeyError) key :address not found in: %{"address" => "123", "public" => "abc"} ...

So I guess my real question is how do I turn

%{"address" => "123", "public" => "abc"}

into

%{:address => "123", :public => "abc"}

so that I can successfully use this:

body.address

is that right?

Upvotes: 0

Views: 2069

Answers (2)

Steve Pallen
Steve Pallen

Reputation: 4527

Its a map with a binary key.

The body.address is a short for accessing an atom key in a map. However, it does not work if the key is not present. Your better to use body[:address] which will return nil if the map does not have the key.

For binary keys, you can use body["address"] to access the struct. Alternative, you can use Map.get(body, "address").

Upvotes: 2

MetaStack
MetaStack

Reputation: 3716

modified code to say this:

    |> Poison.decode!(keys: :atoms!)

That told Poison I want the keys as atoms.

Upvotes: 0

Related Questions