3
votes

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
I think you want field :interests, {:array, :string} in Person?Dogbert

1 Answers

3
votes

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