Reputation: 15
I'm trying to loop over JSON objects and I can't because I have two separate JSON objects in my one JSON file. How would I merge the two objects?
This is how my Json file currently looks like
{"visit_count":280,"employability":"employed","nationality":"Canadian","income":"5555","email":"dsfs@fsfs"}
{"visit_count":280,"employability":"employed","nationality":"Canadian","income":"5555","email":"dsfs@fsfs"}
This is how I'm storing data in my json file
if env["REQUEST_METHOD"] == "POST"
json = template_data.to_json
open('answers.json', 'a') do |file|
file.puts json
end
end
I tried this solution to merge JSON objects
data_hash = JSON.parse(File.read('answers.json'))
data_hash.gsub(/}.*?{/m, '},{')}]")
this is the error that showed up when I tried the above
`load': admin.rb:10: syntax error, unexpected tSTRING_DEND, expecting keyword_end (SyntaxError)
ta_hash.gsub(/}.*?{/m, '},{')}]")
Any help would be greatly appreciated
Upvotes: 0
Views: 1614
Reputation: 5313
Well, first of all, your file is not JSON. If you want to keep it that way and still be capable of parsing the file, I suggest you read each line and add it to an array as a hash, like this:
File.foreach("answers.json").map { |x| JSON.parse(x) }
=> [
{"visit_count"=>280, "employability"=>"employed", "nationality"=>"Canadian", "income"=>"5555", "email"=>"dsfs@fsfs"},
{"visit_count"=>280, "employability"=>"employed", "nationality"=>"Canadian", "income"=>"5555", "email"=>"dsfs@fsfs"}
]
If you want to save proper JSON, you'll need to save an array of objects. The simplest way is to JSON.parse
contents of the file, add a new object to the array, dump it to JSON and save it to the file again, like this:
File.open("answers.json", "r+") do |f|
contents = File.read("answers.json")
prev = contents.empty? ? [] : JSON.parse(contents)
f.write(prev.push(template_data).to_json)
end
Upvotes: 1