我的JSON数组的结构如下:
{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}
在ruby程序中,我希望能够编辑名称的lat和long值。但我不太清楚该怎么做。
sections.each do |user_coords|
user_coords.each do |user, coords|
if user == Usrname then
#Change lat and long value for Usrname
end
end
end
如何做到这一点?
答案 0 :(得分:2)
这是访问JSON中的各个元素的方法:
require 'json'
foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
foo['data'][0]['Chris'][0]['long'] = 5
foo['data'][0]['Chris'][0]['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}
通过将变量用作对象的占位符,可以稍微简化路径:
foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
chris = foo['data'][0]['Chris'][0]
chris['long'] = 5
chris['lat'] = 7
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>7}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}
chris
指向“Chris”哈希,它嵌入在foo
哈希中。对chris
散列的更改发生在foo
内。
如果哈希是正常定义的,它会更干净/清晰和直接:
foo = JSON['{"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18}}}']
foo['data']['Chris']['long'] = 5
foo['data']['Chris']['lat'] = 7
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}
foo
更明确地定义为:
foo = {
'data' => {
'Chris' => {'long' => 5, 'lat' => 7},
'Scott' => {'long' => 9, 'lat' => 18}
}
}
有条件地遍历散列以查找特定的键/值对,使用您的散列:
require 'json'
foo = JSON['{"data":[{"Chris":[{"long":10,"lat":19}]},{"Scott":[{"long":9,"lat":18}]}]}']
user_name = 'Chris'
data = foo['data'].first
data.first.each do |key, value|
if key == user_name
data[user_name].first['long'] = 5
data[user_name].first['lat'] = 6
end
end
foo # => {"data"=>[{"Chris"=>[{"long"=>5, "lat"=>6}]}, {"Scott"=>[{"long"=>9, "lat"=>18}]}]}
必须使用first
(或[0]
)来获取哈希元素才能闻到它。
使用正确定义的哈希会产生如下代码:
foo = JSON['{"data":{"Chris":{"long":10,"lat":19},"Scott":{"long":9,"lat":18}}}']
foo['data'].each do |key, value|
if key == user_name
value['long'] = 5
value['lat'] = 7
end
end
foo # => {"data"=>{"Chris"=>{"long"=>5, "lat"=>7}, "Scott"=>{"long"=>9, "lat"=>18}}}
如何添加另一个名为Bob且long = 10且lat = 20
的人
听起来你并没有很好地掌握操纵/访问哈希,或者如何转换为/来自JSON。你最好把这些基础知识搞定。
不要以JSON开头,而是从Ruby哈希开始:
require 'json'
foo = {
"data" => {
"Chris" => {
"long" => 5,
"lat" => 7
},
"Scott" => {
"long" => 9,
"lat" => 18
}
}
}
添加到您想要的任何其他哈希元素:
bob_hash = {'Bob' => {'long' => 10, 'lat' => 20}}
foo['data'].merge!(bob_hash)
merge!
将bob_hash
添加到foo['data']
。然后,告诉哈希使用to_json
输出其JSON表示。使用熟悉的Ruby结构更容易,并且让Ruby完成转换为JSON的繁重工作,而不是试图对现有的JSON字符串进行字符串操作。如果你有JSON,那么解析它并转换/修改生成的Ruby对象,然后再次输出JSON。
puts foo.to_json
# >> {"data":{"Chris":{"long":5,"lat":7},"Scott":{"long":9,"lat":18},"Bob":{"long":10,"lat":20}}}
我建议也阅读“How to convert JSON to a hash, search for and change a value”,因为它是访问结果哈希值的有用替代方法。
答案 1 :(得分:1)
username = 'Chris'
sections.each do |user_coords|
user_coords.each do |user, coords|
if user == username then
coords.each do |lat_long|
lat_long['lat'] = 123 # Your value here...
lat_long['long'] = 456 # Your value here...
end
end
end
end
sections.to_json # => '[{"Chris":[{"long":456,"lat":123}]}...]'