用ruby修改json文件

时间:2015-07-01 08:09:38

标签: ruby json

我有一个json文件,我需要使用ruby脚本访问和修改。 我知道如何打开一个json,如何编写一个新的,但我可以修改现有的吗?

我已经搜索了一下,但我还没有发现任何有用的东西.. 只有结果才能处理不同的编程语言..

示例:我想修改一个错误的数据,如下所示,Anna的姓氏。

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

提前致谢,

2 个答案:

答案 0 :(得分:6)

将json转换为hash,编辑hash,转换回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\"}]}"

我已经直接修改了哈希,因为我可以看到确切的索引并且通过Hash迭代不是问题。但是在现实世界的例子中,你可能想要通过哈希来寻找密钥,然后修改它,而不是像上面的例子那样直接进行。

您可以使用pretty_generate来打印您的json。这里:

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

答案 1 :(得分:0)

jsonpath gem可以立即使用

JsonPath.for('{"candy":"lollipop"}').gsub('$..candy') {|v| "big turks" }.to_hash

在您的情况下,类似

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

会成功的