6

I am working on Ruby on Rails. I have JSON object like this in my database:

{"data":[
    {"name":"A", "available":"1"},
    {"name":"B", "available":"0"}
]}

I want to update this by adding another record and it should look like:

{"data":[
        {"name":"A", "available":"1"},
        {"name":"B", "available":"0"},
        {"name":"C","available":"1"}
    ]}

How can I do this?

3
  • where is this other record coming from? Commented Mar 15, 2016 at 13:00
  • The other record I am creating based on user input in my website. Commented Mar 15, 2016 at 13:01
  • Is there any thing special about this object? I think this is just a basic array and hash manipulation which you know already if you have used Ruby for a while. You mention "database" and I think you might want to do something with it Commented Mar 15, 2016 at 13:02

2 Answers 2

8

You could try this

json = { "data" => [
         {"name" => "A", "available" => "1"},
         {"name" => "B", "available" => "0"}
       ]}
json["data"].push({"name" => "C", "available" => "1"})
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using ActiveRecord Serialize(Or Rails 5 attribute api), The the value will already be converted to hash.

class Model
 serialize :some_field, JSON
end

record = Model.find(id)

record.some_field ==>
{"data":[
    {"name":"A", "available":"1"},
    {"name":"B", "available":"0"}
]}

record.some_field["data"] << {"name" => "C", "available" => "1"}
record.save

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.