The Issue

There will be times while automating that you might have to read files shared by your client or one of your teammates which are in JSON format. JSON is usually implemented as a replacement for XML for data transmissions. JSON consists of key-value pairs in an array format or can simply be described as hash values.

The Answer

Ruby leverages a gem, which helps in parsing the JSON file to extract the data. Using the “json” gem, it identifies a JSON file and extracts the data from the file. The extracted data can be utilized as per the requirements.

The Code

You must have json gem installed in your machines to run this code. You can install the json gem by using this command – gem install json.

Below is a sample screenshot showcasing the above script execution:


The Result

The above code can be saved as a ruby (.rb) file which does the following

  • Opens the JSON file by using the path specified
  • Reads the data from the JSON file
  • Prints the data from the file

The Takeaway

The only pre-requisite to read a JSON file is to have the json gem installed prior to reading the file. Using the JSON parser you can read data from the JSON file and use the data as required by your scripts.