Parsing the JSON string in Ruby
In the below program, we import the ‘Json’ module using the ‘require’ keyword. we create a json string and then use the parse method in the json(). The parse() method parses the json string and then returns the json string. After that, we can access the values using the names of the keys in the ruby.
Program to parse the JSON string in Ruby:
#importing the JSON Module
require 'json'
data = '{"Name" : "Harsha" ,"Subject":{"1":"Physics","2":"Maths"}}'
json_string = JSON.parse(data)
#Parsing the json string in the ruby
puts json_string["Name"]
#Printing one of the key value in the Json string
puts json_string["Subject"]["1"]
Output
Harsha Physics
Program Explaination :
- In the above code we have to import the module ‘json’ in order to parse with the json file.
- We can import any module we use ‘require’ keyword in json.
- using the JSON.parse() we pass the json string into the method .
- The method parse() is used to parse the string and returns it .
- We can print the value by accessing the keys present in the string .
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.
Contact Us