Change json file with ruby

I have a json file that I need to get and modify using a ruby ​​script. I know how to open json, how to write a new one, but can I modify the existing one?

I've searched for it a bit but haven't found anything useful yet. Only the results are processed in different programming languages.

Example: I want to change incorrect data, for example, 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,

+3


source to share


1 answer


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 changed the hash directly, as I can see that the exact index and iteration through the Hash was not an issue. But in the real world, you might want to go through the hash to look up the key and then change it, rather than doing it like in the example above.



You can use pretty_generate

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

      

+6


source







All Articles