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.rb456 chars20 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