2

I am using ruby version 2.0.0, I have a demo.json file which looks like this:

{ "demo": 
  { 
    "rama" : { "Name": "demo" },
    "krishna" : { "Name": "hare","place": "bharat", "hawa": { "maina": "tota"} } 
  }
}

Now I try to manipulate json file by this way:

require 'json'
options = {}
options[:demo] = "kailash"
 File.open("demo.json","w") do |f|

    f.write(JSON.pretty_generate(options))

end

I want to replace some values and to add some new key-value pairs in the existing JSON file and don't wants to completely replace the entire JSON file. Is there any way to do this?

5
  • 1
    You need to use JSON::parse method, to get the hash object first. Then iterate though the hash, and update the value whatever you want. When done, use Hash#to_json method to make it a JSON object and then write it back to the file. Commented Mar 30, 2014 at 11:46
  • Can you please write this in code format? Commented Mar 30, 2014 at 12:07
  • sure tell me what value you want to update in your .json file ? Commented Mar 30, 2014 at 12:09
  • please update value of "rama" and "krishna" Commented Mar 30, 2014 at 17:33
  • You got the answer.. try to use that to meet your need. Commented Mar 30, 2014 at 17:39

1 Answer 1

6

You must first read and parse your file, then make your changes, and finally you can overwrite the file with the updated object:

require 'json'

options = JSON.parse(IO.read('demo.json'))
options['demo']['kailash'] = { "Name" => "new" }

File.open("demo.json","w") do |f|

    f.write(JSON.pretty_generate(options))

end

Output file:

{
  "demo": {
    "rama": {
      "Name": "demo"
    },
    "krishna": {
      "Name": "hare",
      "place": "bharat",
      "hawa": {
        "main": "tota"
      }
    },
    "kailash": {
      "Name": "new"
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1.. Yes this is the way to solve it, as I said in the comment.
A slightly shorter way to write is File.write('demo.json', JSON.pretty_generate(options))
But what if i wants to update value of existing key like "rama" ?
options['demo']['rama']['new_key'] = ['new_value']

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.