【发布时间】:2014-05-12 16:07:40
【问题描述】:
我正在寻找附加到 ruby 中的 JSON 数组。 JSON 数组如下所示:
{"data" : [{"name":"Chris","long":10,"lat":19}, {"name":"Scott","long":9,"lat":18}]}
我希望能够将另一个对象附加到这个数组,例如
{"name":"John","long":20,"lat":45}
我该怎么做?
【问题讨论】:
我正在寻找附加到 ruby 中的 JSON 数组。 JSON 数组如下所示:
{"data" : [{"name":"Chris","long":10,"lat":19}, {"name":"Scott","long":9,"lat":18}]}
我希望能够将另一个对象附加到这个数组,例如
{"name":"John","long":20,"lat":45}
我该怎么做?
【问题讨论】:
首先以这种方式将 JSON 转换为 Ruby 哈希:
require 'json'
rb_hash = JSON.parse('<your json>');
rb_hash["data"] << { name: "John", long: 20, lat: 45 }
rb_hash.to_json
【讨论】:
=>。您的代码不会解析。您可以使用{ name: "John", long: 20, lat: 45 } 或{ "name" => "John", "long" => 20, "lat" => 45 } 来修复它。
JSON.parse 的调用中,我的意思是您附加到数组的位置。我使用 Ruby 1.9.3 对其进行了测试,它就像我说的那样工作,它不会像你原来的那样工作。
如果你想附加现有的哈希,我们可以这样做 -
hash = {}
我还有另一个哈希值 -
sub_hash = {}
那么-
hash.merge!(sub_hash)
会很好用!!!
【讨论】: