Zubair Nabi
Zubair Nabi

Reputation: 1046

get json values and store that in my table with some specific schema

How can i get specific json values and store that in my table with some specific schema.

e.g i tried

def save_to_payment(conn,result) do
  Poison.decode!(result, as: %Payments.payment{} )
end

with this schema,

schema "payment" do
  field :payment_id, :string
  field :state, :string
  field :amount, :decimal
  timestamps()
end

However the actual Json has many fields, and i just require only few out of them..

I need to map the fields i want to the schema so that i save them in the database

Upvotes: 1

Views: 625

Answers (1)

Dogbert
Dogbert

Reputation: 222188

I'd just pass the raw decoded Map to Payment.changeset/2 and let it handle removing extra fields and doing type casting if needed:

json = "{\"state\":\"CA\",\"payment_id\":1,\"go\":\"here\",\"extra\":\"fields\",\"amount\":123}"
decoded = Poison.decode!(json)
changeset = Payment.changeset(%Payment{}, decoded)
# You can now `Repo.insert!(changeset)` or use it in forms etc.

Upvotes: 1

Related Questions