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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
{ "widget":{ "debug":"on", "window":{ "title":"Sample Konfabulator Widget", "name":"main_window", "width":500, "height":500 }, "image":{ "src":"Images/Sun.png", "name":"sun1", "hOffset":250, "vOffset":250, "alignment":"center" }, "text":{ "data":"Click Here", "size":36, "style":"bold", "name":"text1", "hOffset":250, "vOffset":100, "alignment":"center", "onMouseUp":"sun1.opacity = (sun1.opacity / 100) * 90;" } } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
# run this file as ruby (.rb) file require 'json' # Opening the json file to read the data json_file = File.open "JSON-FILE-PATH" # Reading the data from the json file data_from_file = JSON.load json_file puts data_from_file["widget"]["debug"] puts data_from_file["widget"]["window"] puts data_from_file["widget"]["image"] puts data_from_file["widget"]["text"] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#Result after executing the above code # data_from_file["widget"]["debug"] on # data_from_file["widget"]["window"] {"title":"Sample Konfabulator Widget", "name":"main_window", "width":500, "height":500} # data_from_file["widget"]["image"] {"src":"Images/Sun.png", "name":"sun1", "hOffset":250, "vOffset":250, "alignment":"center"} # data_from_file["widget"]["text"] {"data":"Click Here", "size":36, "style":"bold", "name":"text1", "hOffset":250, "vOffset":100, "alignment":"center", "onMouseUp":"sun1.opacity = (sun1.opacity / 100) * 90;"} |
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.