append to a json file in ruby

To append data to a JSON file in Ruby, we can follow these steps:

  1. Open the JSON file in "append" mode using the File.open method.
  2. Read the JSON data from the file using the JSON.load method.
  3. Modify the JSON data by appending new data to it.
  4. Write the modified JSON data back to the file using the File.write method.

Here's the sample code:

main.rb
require 'json'

# Open the JSON file in append mode
file = File.open('data.json', 'a+')

# Read the JSON data from the file
json_data = file.read
file.rewind

# Parse the JSON data
data = JSON.load(json_data)

# Append new data to the JSON object
data['new_key'] = 'new_value'

# Write the modified JSON data back to the file
File.write('data.json', JSON.pretty_generate(data))

# Close the file
file.close
407 chars
21 lines

In the above code, we first open the JSON file in "append" mode ('a+'), which allows us to both read from and write to the file. We then use the File.read method to read the JSON data from the file, and the JSON.load method to parse it into a Ruby object. We can then modify the object as desired, and use the JSON.pretty_generate method to convert it back into a JSON string with indentation for human readability. Finally, we use the File.write method to write the modified JSON data back to the file, overwriting the previous contents.

related categories

gistlibby LogSnag