5

I am looking to append to a JSON array in ruby. The JSON array looks like this:

{"data" : [{"name":"Chris","long":10,"lat":19}, {"name":"Scott","long":9,"lat":18}]}

I want to be able to append another object to this array e.g

{"name":"John","long":20,"lat":45}

How can I do this?

2 Answers 2

10

First convert the JSON to a Ruby hash this way:

require 'json'
rb_hash = JSON.parse('<your json>');
rb_hash["data"] << { name: "John", long: 20, lat: 45 }

rb_hash.to_json
Sign up to request clarification or add additional context in comments.

11 Comments

You can't put the keys of a hash in strings in Ruby, not unless you use the fat arrow =>. Your code won't parse. You can fix it by using { name: "John", long: 20, lat: 45 }, or { "name" => "John", "long" => 20, "lat" => 45 }.
you can't define json like that in ruby. it will give sytax error. it should be as string. if it is a string, JSON.parse will work.
Wait, how do I then write it to the file?
@user1614998 I don't mean in the call to JSON.parse, I mean where you append to the array. I tested it out using Ruby 1.9.3 and it works like the way I said, it won't work the way you had it originally.
@Cj1m try JSON.parse(File.open('<file_path>').read) to read json
|
2

If you want to append existing hash, we can do as below-

hash = {} 

I have another hash as-

sub_hash = {}

then-

hash.merge!(sub_hash) 

will work great!!!

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.