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?
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
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!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With