copy a json file in ruby

To copy a JSON file in Ruby, you can use the File class to read from the source file and write to a new file.

Here's an example code snippet that shows how to copy a JSON file named "input.json" to a new file named "output.json":

main.rb
require 'json'

# open the source file for reading
source_file = File.open('input.json', 'r')

# read the contents of the source file and parse as JSON
source_data = JSON.parse(source_file.read)

# close the source file
source_file.close

# open the target file for writing
target_file = File.open('output.json', 'w')

# write the JSON data to the target file
target_file.write(JSON.pretty_generate(source_data))

# close the target file
target_file.close
456 chars
20 lines

In the above code, we first open the source file "input.json" for reading. We then read the contents of the source file and parse them as JSON using the JSON.parse method.

Next, we create a new file called "output.json" using the File.open method with the 'w' flag, which allows us to write to the file.

We then use the JSON.pretty_generate method to convert the parsed JSON data to a string in a pretty printed format, and write this data to the target file using the target_file.write method.

Finally, we close both the source and target files using the close method.

gistlibby LogSnag