Ruby无法附加到JSON文件

时间:2018-04-04 12:32:34

标签: arrays json ruby hash

我正在尝试将JSON对象附加到现有的JSON文件中。我使用了StackOverflow和谷歌,但我无法找到答案。这是我的代码:

json = File.read(File.join( File.dirname(__FILE__),"configs/#{enviroment}.json"))

rb_hash = JSON.parse(json);

rb_hash["searchExamples"] << { name: "John", long: 20, lat: 45 }

rb_hash.to_json

但我得到错误:

undefined method `<<' for #<Hash:0x007ffa93124bd0> (NoMethodError)
Did you mean?  <

1 个答案:

答案 0 :(得分:0)

rb_hash["searchExamples"]是哈希值,而@axiac表示在ruby中Hash类上没有<<方法。使用Hash#merge连接两个哈希:

json = File.read(File.join( File.dirname(__FILE__),"configs/#{enviroment}.json"))

rb_hash = JSON.parse(json);
rb_hash["searchExamples"] = rb_hash["searchExamples"].merge({ name: "John", long: 20, lat: 45 })
# or rb_hash["searchExamples"].merge!({ name: "John", long: 20, lat: 45 })

File.write(File.join( File.dirname(__FILE__),"configs/#{enviroment}.json"), rb_hash.to_json)

此外,您可能希望使用漂亮的生成宝石,如NeatJSONJSON#pretty_generate,以便在文件中获得更好的json输出