I have a json file that I need to access and modify with a ruby script. I know how to open a json, how to write a new one, but can I modify an existing one?
I have searched for it a bit, but I have not found anything helpfull yet.. Only results treats on different programming languages ..
exemple : I want to modify a wrong data, like below, Anna's last name.
employee.json
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
=>
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"David"},
{"firstName":"Peter", "lastName":"Jones"}
]}
Thanks in advance,
Convert json to hash, edit hash, convert back to json:
require 'json'
a = '{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}'
# Converting JSON to Hash
hash = JSON.parse a
# => {"employees"=>[{"firstName"=>"John", "lastName"=>"Doe"}, {"firstName"=>"Anna", "lastName"=>"Smith"}, {"firstName"=>"Peter", "lastName"=>"Jones"}]}
# Modifying Hash as required
hash["employees"][1]["lastName"] = "David"
# Modified Hash
hash
# => {"employees"=>[{"firstName"=>"John", "lastName"=>"Doe"}, {"firstName"=>"Anna", "lastName"=>"David"}, {"firstName"=>"Peter", "lastName"=>"Jones"}]}
# Converting Hash back to JSON
hash.to_json
# "{\"employees\":[{\"firstName\":\"John\",\"lastName\":\"Doe\"}, {\"firstName\":\"Anna\",\"lastName\":\"David\"}, {\"firstName\":\"Peter\",\"lastName\":\"Jones\"}]}"
I have directly modified the hash as I can see the exact index and iterating through Hash was not the question. But in real world example you may want to go through the Hash to look for key and then modify it, instead of doing to directly as in above example.
You can use pretty_generate
to pretty print your json. Here:
hash
# => {"employees"=>[{"firstName"=>"John", "lastName"=>"Doe"}, {"firstName"=>"Anna", "lastName"=>"David"}, {"firstName"=>"Peter", "lastName"=>"Jones"}]}
puts JSON.pretty_generate hash
#{
# "employees": [
# {
# "firstName": "John",
# "lastName": "Doe"
# },
# {
# "firstName": "Anna",
# "lastName": "David"
# },
# {
# "firstName": "Peter",
# "lastName": "Jones"
# }
# ]
#}
jsonpath gem can do it out of the box
JsonPath.for('{"candy":"lollipop"}').gsub('$..candy') {|v| "big turks" }.to_hash
in your case something like
require 'jsonpath'
a = '{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}'
JsonPath.for(a).gsub('$.employees[1].lastName') {|v| "David" }.to_hash
will do the trick
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