0

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

answers.json

{"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

1
  • When do you want to merge these objects, while saving to file or while reading from file? Commented Oct 26, 2018 at 1:38

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.