Ruby Convert Array of Hashes to JSON

1. Introduction

JSON, or JavaScript Object Notation, is a standardized format commonly used for transmitting data in web applications. In Ruby, converting an array of hashes to JSON involves serializing the array, which means transforming it from Ruby objects into a string that follows the JSON format specification.

2. Program Steps

1. Confirm the availability of the JSON library in your Ruby setup.

2. Define the array of hashes you intend to convert.

3. Serialize the array using the to_json method provided by the JSON library.

4. Output the resulting JSON string to verify the conversion.

3. Code Program

# Step 1: Ensure the JSON library is loaded
require 'json'
# Step 2: Define the array of hashes
array_of_hashes = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]
# Step 3: Serialize the array of hashes to JSON
json_data = array_of_hashes.to_json
# Step 4: Output the JSON string
puts json_data

Output:

[{"name":"John","age":30},{"name":"Jane","age":25}]

Explanation:

1. require 'json' is used to include the JSON library, which provides the to_json method necessary for serialization.

2. array_of_hashes contains the initial data structure, an array where each element is a hash with key-value pairs.

3. array_of_hashes.to_json converts the array of hashes into a JSON-formatted string.

4. puts json_data prints out the serialized data, allowing us to see the JSON representation of our original Ruby array of hashes.


Comments