Cj1m
Cj1m

Reputation: 815

Appending to JSON array in Ruby

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?

Upvotes: 5

Views: 18715

Answers (2)

S.Yadav
S.Yadav

Reputation: 4509

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!!!

Upvotes: 2

Saravanan
Saravanan

Reputation: 509

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

Upvotes: 10

Related Questions