How to add new key/value pair to existing JSON object in Ruby -
how append new key/value pair existing json object in ruby?
my output is
{ "2d967df3-ee07-4e40-8f65-7bbff59bbb7e": { "name": "book1", "author": "author1" } }
i want achieve when add new key/value pair
{ "2d967df3-ee07-4e40-8f65-7bbff59bbb7e": { "name": "book1", "author": "author1" }, "c55a3632-9bed-4a41-ae40-c1abfe0f332a": { "name": "book2", "author": "author2" } }
method write json file
def create_book(name, author) temphash = { securerandom.uuid => { "name" => name, "author" => author } } file.open("./books/book.json","w") |f| f.write(json.pretty_generate(temphash)) end end
how append new key/value pair existing json object in ruby?
if want add existing file should read json first, extract data it, add new hash array. maybe solve 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") |f| f.write(json.pretty_generate(data_from_json << temphash)) end end
there other ways manipulating json common string safety should extract data , create new json one.
Comments
Post a Comment