HorseLeg
HorseLeg

Reputation: 47

How do I append/add data to an JSON file with Ruby

So I'm trying to add info to my .json file, a first name and a last name, from just running the script via terminal in kali linux.

I have not have had much progress I have been searching online for the past 5 hours to find a way to fix this but there has not been much progress. Which leaves me here to post this, anyone know how to fix this error?

Traceback (most recent call last):
        4: from /root/Desktop/JSON_thingy.rb:8:in `<main>'
        3: from /root/Desktop/JSON_thingy.rb:8:in `open'
        2: from /root/Desktop/JSON_thingy.rb:9:in `block in <main>'
        1: from /usr/lib/ruby/vendor_ruby/json/common.rb:156:in `parse'
/usr/lib/ruby/vendor_ruby/json/pure/parser.rb:118:in `parse': source in not valid JSON! (JSON::ParserError)
require 'json'
require 'json/pure'

json = {"first_name" => "john", "last_name" => "doe"}

initial_json = File.read('/root/Desktop/jsonDatabase.json')

File.open("/root/Desktop/jsonDatabase.json","w") do |f|
  f.puts JSON.pretty_generate(JSON.parse(initial_json) << json )
end 
[
{
 "first_name": "albert",
 "last_name": "einstein"
},
{
 "first_name": "edgar",
 "last_name": "poe"
}
]

Upvotes: 1

Views: 1576

Answers (2)

lacostenycoder
lacostenycoder

Reputation: 11236

The previous answer is cleaner and I would recommend using that. However, the trace error clearly tells you what the problem is, this line:

/usr/lib/ruby/vendor_ruby/json/pure/parser.rb:118:in `parse': 
source in not valid JSON! (JSON::ParserError)

The part of your code which has errored is this:

JSON.parse(initial_json)

So you need to first make sure the data in the file you're loading is actually valid JSON. You can either use the jsonlint ruby gem or other online linters like https://jsonlint.com/ or if you're a duck duck go user this, either of which will "beautify" your json for you.

UPDATE

If you use ruby jsonlint you may get a deprecation warning, you can safely ignore it. But it's because one of its' dependencies trollop is throwing the deprecation warning. I have opened a pull request to fix it. But it looks like it might not be maintained, last commit is almost 2 years ago. *Sigh

Upvotes: 1

spickermann
spickermann

Reputation: 107142

Of course, simply joining two JSON strings together don't work and would result in an invalid JSON. In your example, the hash you try to add would not end up in the array but behind.

The correct way is to read the existing JSON file and parse it into a RUBY data structure and add the new hash in Ruby to the array before writing everything back to JSON.

require 'json'

filename = '/root/Desktop/jsonDatabase.json'

hash = { "first_name" => "john", "last_name" => "doe" }

array = JSON.parse(File.read(filename)
array << hash

File.open(filename, 'w') do |f|
  f.write(JSON.pretty_generate(array))
end

Upvotes: 4

Related Questions