Appending to JSON array in Ruby

15,156

Solution 1

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

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

Share:
15,156
Cj1m
Author by

Cj1m

Updated on June 04, 2022

Comments

  • Cj1m
    Cj1m almost 2 years

    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?

  • Admin
    Admin about 10 years
    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 }.
  • Saravanan
    Saravanan about 10 years
    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.
  • Cj1m
    Cj1m about 10 years
    Wait, how do I then write it to the file?
  • Admin
    Admin about 10 years
    @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.
  • Admin
    Admin about 10 years
    @Cj1m open up the file in Ruby and replace its contents.
  • Cj1m
    Cj1m about 10 years
    like this: File.open("public/test.json", "w") do |f| f.write(rb_hash) end
  • Admin
    Admin about 10 years
    @Cj1m something like that, sure.
  • Saravanan
    Saravanan about 10 years
    @Cupcake okay, sorry i missed it.
  • Cj1m
    Cj1m about 10 years
    @Cupcake That doesn't seem to work, here is a paste bin of my code: pastebin.com/dyGmMmW7
  • Saravanan
    Saravanan about 10 years
    @Cj1m try JSON.parse(File.open('<file_path>').read) to read json
  • Cj1m
    Cj1m about 10 years
    @Saravanan Do you know how I can make "name:" in the JSON script equal to a variable in Ruby e.g var: "John" ?