JSON implementation for Ruby

Description

This is a implementation of the JSON specification according to RFC 4627. You can think of it as a low fat alternative to XML, if you want to store data to disk or transmit it over a network rather than use a verbose markup language.

Starting from version 1.0.0 on there will be two variants available:

Both variants of the JSON generator escape all non-ASCII an 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. This means that generated JSON text is encoded as UTF-8 (because ASCII is a subset of UTF-8) and at the same time avoids decoding problems for receiving endpoints, that don't expect UTF-8 encoded texts. On the negative side this may lead to a bit longer strings than necessarry.

It's also easy to extend JSON data types for arbitrary Ruby classes (including your own) like this:

class Range
  def to_json(*a)
    {
      'json_class'   => self.class.name,
      'data'         => [ first, last, exclude_end? ]
    }.to_json(*a)
  end

  def self.json_create(o)
    new(*o['data'])
  end
end

Now Range instances can be serialized/deserialized:

JSON.parse((1..10).to_json) == (1..10)

A lot of additional information about JSON can be found Douglas Crockford's JSON site.

Installation

The library can be installed via rubygems:

# gem install json

If you have to use the pure variant, you can use:

# gem install json_pure

The gem and the source archive can also be downloaded directly from rubyforge.org.

Usage

If you require JSON like this:

require 'json'

JSON first tries to load the extension variant. If this fails, the pure variant is loaded and used.

To determine, which variant is active you can use the follwing methods:

If you want to enforce loading of a special variant, use

require 'json/ext'

to load the extension variant. Or use

require 'json/pure'

to use the pure variant.

You can choose to load a set of common additions to ruby core's objects if you

  require 'json/add/core'

To get the best compatibility to rails' JSON implementation, you can

    require 'json/add/rails'

Both of the additions attempt to require 'json' (like above) first, if it has not been required yet.

Author

Florian Frank <flori@ping.de>

License

This is software is distributed under the same license as Ruby itself. See http://www.ruby-lang.org/en/LICENSE.txt.

Valid XHTML 1.0 Transitional