gpt4 book ai didi

ruby - 用ruby修改json文件

转载 作者:数据小太阳 更新时间:2023-10-29 07:28:29 32 4
gpt4 key购买 nike

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

我已经搜索了一下,但我还没有找到任何有用的东西......只有结果对待不同的编程语言..

例子:我想修改一个错误的数据,如下图,Anna的姓。

员工.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"}
]}

提前致谢

最佳答案

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

我已经直接修改了散列,因为我可以看到确切的索引并且遍历散列不是问题。但在现实世界的示例中,您可能希望通过哈希来查找 key 然后修改它,而不是像上面的示例那样直接执行。

您可以使用 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"
# }
# ]
#}

关于ruby - 用ruby修改json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155893/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com