GitHub

CI

Description

This is an implementation of the JSON specification according to RFC 7159 http://www.ietf.org/rfc/rfc7159.txt .

The JSON generator generate UTF-8 character sequences by default. If an :ascii_only option with a true value is given, they escape all non-ASCII and control characters with \uXXXX escape sequences, and support UTF-16 surrogate pairs in order to be able to generate the whole range of unicode code points.

All strings, that are to be encoded as JSON strings, should be UTF-8 byte sequences on the Ruby side.

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add json

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install json

Basic Usage

To use JSON you can

require 'json'

Now you can parse a JSON document into a ruby data structure by calling

JSON.parse(document)

If you want to generate a JSON document from a ruby data structure call

JSON.generate(data)

You can also use the pretty_generate method (which formats the output more verbosely and nicely).

Casting non native types

JSON documents can only support Hashes, Arrays, Strings, Integers and Floats.

By default if you attempt to serialize something else, JSON.generate will search for a #to_json method on that object:

Position = Struct.new(:latitude, :longitude) do
  def to_json(state = nil, *)
    JSON::State.from_state(state).generate({
      latitude: latitude,
      longitude: longitude,
    })
  end
end
JSON.generate([
  Position.new(12323.234, 435345.233),
  Position.new(23434.676, 159435.324),
]) # => [{"latitude":12323.234,"longitude":435345.233},{"latitude":23434.676,"longitude":159435.324}]

If a #to_json method isn't defined on the object, JSON.generate will fallback to call #to_s:

"JSON.generate(Object.new) # => "#

Read the original on github.com ↗