Ruby: manipulate json
I started a project, which used an existing json file full of data. Because not all data was necessary, I decided to clean it up and rename some keywords. Instead of doing that manually, I created a ruby script.
Here is an example of the input and the prefered output json:
This is the script used for modifying this json file:
First, we read the input file (1)
and parse it (2)
. We create an empty array that we will use for storing our new json (3)
. Now we loop over each existing json entry (4)
, create a new object, and fill that object with the information we want to keep (5)
. Once we have looped over all the entries, we are going to save the file as output.json
. To do this, open that file as writable (6)
. If the file does not exist yet, it will automatically be created. For extra readability, we can pretty print the json using the pretty_generate
function (7)
. This will ouput the file as listed above.