Parsing the json file in ruby
In the below code we will parse a json file by giving the path of the json file using the open() method the open() method in the ruby helps us to open the file then we read the contents of the file in the ruby using the read in the ruby . After reading the contents from the file the contents in the file will be stored in the object . Then we pass the contents object into the parse method which is available in the ruby json .
Program to parsing the json file in ruby:
file_name.json: {“name” : “Harsha” , “subject” : “Maths” , “Roll” :{“1″:”Harsha” , “2” : “Vardhan” , “3” : “Krishna” } }
#Importing the module json
require "json"
#Opening the File named "file_name.json"
file = open("file_name.json")
#Reading the contents from the file
parsed = file.read
#Parsing the json contents
new_string = JSON.parse(parsed)
#Printing the contents
puts new_string
#Itearting over each elements in the JSON String
for i in new_string
puts i
end
Output
{"name"=>"Harsha", "subject"=>"Maths", "Roll"=>{"1"=>"Harsha", "2"=>"Vardhan", "3"=>"Krishna"}}
name
Harsha
subject
Maths
Roll
{"1"=>"Harsha", "2"=>"Vardhan", "3"=>"Krishna"}
Program Explaination:
- In the above program we have read the json file using the file methods such as open and read methods in the ruby which are used for the file handling methods
- Firstly we have imported the JSON module in the ruby using the require keyword .
- Then we have passed the path of the file “file_name.json” into the open method .
- By using the read method we have read the contents of the file available in the json file .
- The contents present in the file will be stored in the single object .
- Then we have printed the contents by itearting through the object with the help of the for loop.
In this way we can parse the json file which is available in the ruby.
How to parse JSON in Ruby?
JSON stands for JavaScript Object Notation. In the JSON the data is stored in the form of a key-value pair. we can parse the JSON file in various languages with the help of the respective modules available in the languages. Let’s suppose when we want to parse a JSON file in the Python programming language then we use some of the libraries like JSON and Pandas. In Ruby to parse the Json we need to import the required libraries such as “JSON” using the required keyword in the ruby.
We can read the JSON string as well as the JSON file in the ruby using the ‘JSON’ in the ruby.