Ruby JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and write and easy for machines to parse and generate. Ruby includes a library to parse JSON.

Here is a tutorial on how to work with JSON in Ruby:

1. Parsing JSON

First, you need to require the json library:

require 'json'

Then you can parse a JSON string like this:

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

puts parsed["name"]  # Outputs: John

JSON.parse takes a JSON string and converts it into a Ruby hash.

2. Generating JSON

You can also generate a JSON string from a Ruby hash like this:

require 'json'

hash = {"name" => "John", "age" => 30, "city" => "New York"}
json_string = JSON.generate(hash)

puts json_string  # Outputs: {"name":"John","age":30,"city":"New York"}

JSON.generate takes a Ruby hash and converts it into a JSON string.

3. Reading JSON from a File

You can read JSON from a file like this:

require 'json'

file = File.read('input.json')
data = JSON.parse(file)
puts data["name"]  # Outputs: John

4. Writing JSON to a File

Similarly, you can write JSON to a file like this:

require 'json'

hash = {"name" => "John", "age" => 30, "city" => "New York"}
File.open("output.json","w") do |f|
  f.write(JSON.pretty_generate(hash))
end

Here, JSON.pretty_generate is used instead of JSON.generate to format the JSON string in a more human-readable way.

Remember that JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. This makes it an ideal data-interchange language.

  1. Parsing JSON in Ruby: Ruby provides a built-in JSON module for parsing JSON strings.

    require 'json'
    json_string = '{"name": "John", "age": 30}'
    parsed_data = JSON.parse(json_string)
    
  2. Generating JSON in Ruby: Use the to_json method to convert Ruby objects to JSON format.

    data = { name: 'Jane', age: 25 }
    json_string = data.to_json
    
  3. Ruby JSON library: The JSON module is part of the Ruby standard library and handles JSON encoding and decoding.

    require 'json'
    
  4. Working with JSON objects in Ruby: Once parsed, JSON objects in Ruby are treated like regular hashes and arrays.

    puts parsed_data['name']  # Accessing JSON object properties
    
  5. Ruby JSON parse vs. load: Both JSON.parse and JSON.load can be used for parsing JSON, but load can handle additional options.

    parsed_data = JSON.parse(json_string)
    parsed_data = JSON.load(json_string)
    
  6. Serializing Ruby objects to JSON: Customize serialization using to_json and as_json methods.

    class Person
      attr_accessor :name, :age
    
      def as_json(options = {})
        { name: name, age: age }
      end
    end
    
    person = Person.new(name: 'Alice', age: 28)
    json_string = person.to_json
    
  7. Deserializing JSON to Ruby objects: Implement a custom json_create method for deserialization.

    class Person
      def self.json_create(data)
        new(name: data['name'], age: data['age'])
      end
    end
    
    person = JSON.parse(json_string, object_class: Person)
    
  8. Handling JSON arrays in Ruby: JSON arrays can be parsed and manipulated like Ruby arrays.

    json_array = '[1, 2, 3]'
    array = JSON.parse(json_array)
    
  9. Ruby JSON pretty print: Use the JSON.pretty_generate method for human-readable JSON.

    data = { name: 'Bob', age: 35 }
    pretty_json = JSON.pretty_generate(data)
    
  10. JSON encoding and decoding in Ruby: Encoding and decoding are done with JSON.dump and JSON.load.

    encoded = JSON.dump(data)
    decoded = JSON.load(encoded)
    
  11. Reading JSON from a file in Ruby: Read JSON data from a file using File and JSON modules.

    require 'json'
    
    file_data = File.read('data.json')
    parsed_data = JSON.parse(file_data)
    
  12. Ruby JSON gem usage: The json gem provides additional features and optimizations for working with JSON.

    gem 'json', require: 'json'
    
  13. Ruby JSON API requests: Fetch and parse JSON data from an API using tools like Net::HTTP.

    require 'json'
    require 'net/http'
    
    uri = URI('https://api.example.com/data')
    response = Net::HTTP.get(uri)
    parsed_data = JSON.parse(response)
    
  14. Validating JSON in Ruby: Ruby's JSON::Validator can be used to validate JSON against a schema.

    require 'json'
    require 'json-schema'
    
    schema = {
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'integer' }
      }
    }
    
    data = { name: 'John', age: 30 }
    JSON::Validator.validate!(schema, data)