How to Write JSON in Ruby: Simple Guide with Examples
In Ruby, you can write JSON by using the
JSON module from the standard library. First, require 'json', then use JSON.generate(object) or object.to_json to convert Ruby objects like hashes or arrays into JSON strings.Syntax
To write JSON in Ruby, you need to require the json library. Then, you can convert Ruby objects to JSON strings using JSON.generate(object) or object.to_json. Both methods turn hashes, arrays, and other serializable objects into JSON format.
require 'json': Loads the JSON library.JSON.generate(object): Converts a Ruby object to a JSON string.object.to_json: Another way to convert an object to JSON (requiresrequire 'json').
ruby
require 'json' ruby_hash = { name: "Alice", age: 30, city: "Wonderland" } json_string = JSON.generate(ruby_hash) puts json_string
Output
{"name":"Alice","age":30,"city":"Wonderland"}
Example
This example shows how to convert a Ruby hash to a JSON string and print it. It demonstrates the basic usage of JSON.generate and to_json methods.
ruby
require 'json' person = { name: "Bob", age: 25, hobbies: ["reading", "cycling"] } # Using JSON.generate json1 = JSON.generate(person) puts json1 # Using to_json json2 = person.to_json puts json2
Output
{"name":"Bob","age":25,"hobbies":["reading","cycling"]}
{"name":"Bob","age":25,"hobbies":["reading","cycling"]}
Common Pitfalls
Common mistakes when writing JSON in Ruby include:
- Forgetting to
require 'json', which causes errors when calling JSON methods. - Trying to convert objects that are not serializable, like custom classes without
to_jsonmethods. - Using symbols as keys in hashes without converting them, which JSON converts to strings automatically but can confuse beginners.
Always ensure your data is serializable and require 'json' is included.
ruby
require 'json' # Wrong: forgetting to require json # json_str = JSON.generate({a: 1}) # This will cause an error # Right: json_str = JSON.generate({a: 1}) puts json_str # Wrong: trying to convert an unserializable object class Person attr_accessor :name def initialize(name) @name = name end end person = Person.new("Eve") # JSON.generate(person) # This raises an error # Right: convert to hash first json_str = JSON.generate({name: person.name}) puts json_str
Output
{"a":1}
{"name":"Eve"}
Quick Reference
Here is a quick summary of how to write JSON in Ruby:
| Action | Code Example |
|---|---|
| Load JSON library | require 'json' |
| Convert hash to JSON string | JSON.generate({key: 'value'}) |
| Convert array to JSON string | JSON.generate([1, 2, 3]) |
| Use to_json method | {a: 1}.to_json |
| Print JSON string | puts JSON.generate({name: 'Alice'}) |
Key Takeaways
Always require 'json' before using JSON methods in Ruby.
Use JSON.generate or to_json to convert Ruby objects to JSON strings.
Make sure objects are serializable; convert custom objects to hashes first.
Symbols in hashes become strings in JSON automatically.
Common errors come from missing require or unserializable objects.