我有这个json代码:
{
"kind": "something",
"rules": [
{
"rule1": [
"something1",
"something2",
"something3"
],
"rule2": "something"
}
]
}
我想在rule1中添加一些东西4。我怎么能在Ruby中做到这一点?
感谢
答案 0 :(得分:0)
让json_string
成为您的JSON字符串
require 'json'
h = JSON.parse(json_string)
h["rules"][0]["rule1"] << "something4"
答案 1 :(得分:0)
你的问题是你的JSON设计得很差,无法找到特定的密钥,因为各种规则实际上都包含在一个数组中。在您的示例中,您只有一个,但如果您有更多的数组元素,那么您必须找到要修改的 right 数组元素。可以通过Enumerable#each_with_index或相关方法完成大量工作,但如果您对JSON的结构有信心,可以使用快捷方式。
require 'json'
json = <<~'EOF'
{
"kind": "something",
"rules": [
{
"rule1": [
"something1",
"something2",
"something3"
],
"rule2": "something"
}
]
}
EOF
# Get the first array from "rules", and append the string
# to the array inside the hash value referenced by the
# "rule1" key.
hash['rules'].first['rule1'] << 'something4'
puts JSON.pretty_generate(hash)
{ "kind": "something", "rules": [ { "rule1": [ "something1", "something2", "something3", "something4" ], "rule2": "something" } ] }
在现实世界中,您可能必须遍历 rules 数组才能找到要修改的数组元素的索引。之后,您可以找到 rule1 键,并将您想要的值附加到值的哈希值。
答案 2 :(得分:0)
说您将该代码分配给变量
settings = {
"kind": "something",
"rules": [
{
"rule1": [
"something1",
"something2",
"something3"
],
"rule2": "something"
}
]
}
你可以这样做:
settings["rules"][0]["rule1"] << "test"