How To Convert String To Json In Ruby

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is widely used for data exchange between the client and the server. In this blog post, we will learn how to convert a string to JSON format in Ruby.

Converting a String to JSON

To convert a string to JSON in Ruby, you would need to use the json gem. The json gem is part of Ruby’s standard library, so you don’t need to install it separately.

First, you will need to require the json gem in your Ruby script using the following line of code:

require ‘json’

Next, let’s assume that you have a string that you want to convert to JSON format. The string looks like this:

string_data = ‘{“name”:”John”, “age”:30, “city”:”New York”}’

To convert the string to JSON, you will need to use the JSON.parse() method provided by the json gem. The method takes the string as an argument and returns the parsed JSON data. Here’s how you can parse the string_data:

  require 'json'

  string_data = '{"name":"John", "age":30, "city":"New York"}'
  json_data = JSON.parse(string_data)

The json_data variable now contains the JSON representation of the string. You can access the individual values in the JSON object using the key names, like this:

  puts json_data['name'] # Output: John
  puts json_data['age']  # Output: 30
  puts json_data['city'] # Output: New York

Error Handling

If the string you’re trying to parse is not a valid JSON, the JSON.parse() method will raise a JSON::ParserError exception. To handle this gracefully, you can use a begin-rescue block. Here’s an example:

  require 'json'

  invalid_string_data = 'This is not a valid JSON string.'

    json_data = JSON.parse(invalid_string_data)
  rescue JSON::ParserError => e
    puts "Failed to parse the JSON string: #{e.message}"

In this example, if the JSON.parse() method fails to parse the invalid_string_data, the rescue block will catch the exception and display an error message.


In this blog post, we have learned how to convert a string to JSON format in Ruby using the json gem. We have also seen how to handle errors raised by the JSON.parse() method in case the string is not a valid JSON. Remember to always require the json gem and use a begin-rescue block for error handling when parsing JSON strings in Ruby.