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"
# }
# ]
#}