[英]How to add new key/value pair to existing JSON object in Ruby
How could I append a new key/value pair to an existing JSON object in Ruby?如何将新的键/值对附加到 Ruby 中的现有 JSON 对象?
My output is:我的输出是:
{
"2d967df3-ee07-4e40-8f65-7bbff59bbb7e": {
"name": "Book1",
"author": "Author1"
}
}
I want to achieve something like this when I add a new key/value pair:当我添加一个新的键/值对时,我想实现这样的目标:
{
"2d967df3-ee07-4e40-8f65-7bbff59bbb7e": {
"name": "Book1",
"author": "Author1"
},
"c55a3632-9bed-4a41-ae40-c1abfe0f332a": {
"name": "Book2",
"author": "Author2"
}
}
This is my method to write to a JSON file:这是我写入 JSON 文件的方法:
def create_book(name, author)
tempHash = {
SecureRandom.uuid => {
"name" => name,
"author" => author
}
}
File.open("./books/book.json","w") do |f|
f.write(JSON.pretty_generate(tempHash))
end
end
To clarify, I need to add a second entry to the original file.为了澄清,我需要在原始文件中添加第二个条目。 I tried using
append
( <<
), and that's where my code fails:我尝试使用
append
( <<
),这就是我的代码失败的地方:
file = File.read("./books/book.json")
data_hash = JSON.parse(file)
newJson = data_hash << tempHash
How could I append a new key/value pair to existing JSON object in Ruby?
如何将新的键/值对附加到 Ruby 中的现有 JSON 对象?
If you want to add it to an existing file then you should read the JSON first, extract data from it, then add a new hash to an array.如果要将其添加到现有文件中,则应首先读取 JSON,从中提取数据,然后将新的哈希添加到数组中。
Maybe something like this will solve your problem:也许这样的事情会解决你的问题:
def create_book(name, author)
tempHash = {
SecureRandom.uuid => {
"name" => name,
"author" => author
}
}
data_from_json = JSON[File.read("./books/book.json")]
data_from_json = [data_from_json] if data_from_json.class != Array
File.open("./books/book.json","w") do |f|
f.write(JSON.pretty_generate(data_from_json << tempHash))
end
end
There are also some other ways like manipulating the JSON as a common string but for safety you should extract the data and then create a new JSON file.还有一些其他方法,例如将 JSON 处理为公共字符串,但为了安全起见,您应该提取数据,然后创建一个新的 JSON 文件。
If you need the new key/value pair to be in the same JSON element as the previous data, instead of shoveling ( <<
) the hashes together, merge them.如果您需要新的键/值对与之前的数据位于同一个 JSON 元素中,而不是将散列 (
<<
) 铲到一起,而是将它们合并。
Additionally this can allow you to put the new key/value pair in the start of the element or in the end, by flipping which hash you merge first.此外,这可以让您通过翻转首先合并的哈希,将新的键/值对放在元素的开头或结尾。
So, take Maxim's solution from Apr 14 '15, but modify to merge the two hashes together.因此,采用 Maxim 2015 年 4 月 14 日的解决方案,但进行修改以将两个散列合并在一起。
data_from_json = JSON[http://File.read("./books/book.json")]
File.open("./books/book.json","w") do |f|
f.write(JSON.pretty_generate([data_from_json.merge(tempHash)])
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.