3

I am using Elixir to retrieve a json from an external API and store it in a Postgresql database. I am using Poison to decode the json into Elixir Ecto (2.0) schemas. It is working well except for one aspect: an element of the json is a List without any keys. I am at a loss for how to map this element to an Elixir struct.

The json:

{"name": "Joe Random"
 "address": {
   "street": "123 Main St",
   "city": "Smalltown"
   },
 "interests": [
   "Biking",
   "Movies"
   ]
}

This json takes the form of a struct (person) with an embedded struct (address) and an embedded list (interests). I want to model this structure with Ecto.Schemas so I can load the json into it. The person and address structs are simple:

defmodule Person do
  use Ecto.Schema

  schema "person" do
    field :name, :string
    embeds_one :address, Address
  end
end

defmodule Address do
  use Ecto.Schema

  embedded_schema do
    field :street, :string
    field :city, :string
  end
end

I can use Poison.decode to load these structs:

Poison.decode!(json, as person: %Person{address: %Address{}})

However, how do I model and store the "interests": from the json? It's just a simple single-value list without any keys. Can I turn it into a map that I can then model with Ecto.Schema? Has anyone encountered an issue like this before?

Any guidance would be appreciated!

1
  • 2
    I think you want field :interests, {:array, :string} in Person? Commented Jun 9, 2016 at 3:31

1 Answer 1

3

Thank you, Dogbert. I added a field of type {:array, :string} for the "interests" element of the json to the Person Ecto.schema. I successfully loaded the struct from the json using Poison!

defmodule Person do
  use Ecto.Schema

  schema "person" do
    fields :name, :string
    embeds_one :address, Address
    fields :interests, {:array, :string}
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.