Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 604
Cj1m Avatar asked Dec 25 '22 11:12

Cj1m


2 Answers

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
like image 107
Saravanan Avatar answered Dec 28 '22 06:12

Saravanan


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

like image 27
S.Yadav Avatar answered Dec 28 '22 06:12

S.Yadav