An open-source Ruby library for JSON parsing and encoding.
Github Install 0.4.0

Getting Started

Wankel makes it easy to parse and encode Objects and deal with JSON streams.

A Tree model parser/encoder interface (ie. DOM tree in libxml2) and a Event based parser/encoder interface (ie. SAX interface in libxml2) are provided.

Installation

Wankel requires Ruby 2.0 or greater.

Currently the only dependency is YAJL 2

OS X
brew install yajl
gem install wankel
Ubuntu 14.04+
apt-get install libyajl-dev
gem install wankel
Arch Linux
pacman -S yajl
gem install wankel
Source
curl -L -o 'yajl-2.1.0.tar.gz' http://github.com/lloyd/yajl/tarball/2.1.0
tar -xf yajl-2.1.0.tar.gz
cd lloyd-yajl-*
./configure
make install

gem install wankel

Parsing

Viking.Model extends Backbone.Model adding naming, associations, data type coerions, selection, and modifies sync to work with Ruby on Rails out of the box.

 

Your are not required to pass a name. In this example the name "ship" allows Viking automatically read and build the associations and generate any urls.

Wankel.parse('{"key": "value"}') # => {"key" => "value"}

# Options

Streaming

belongsTo takes and array of names for the associations. By default a get('fleet') in the example would return undefined on a new instance of the model.

You can set the fleet with the normal set function or through the inital attributes. Both accept either an model or the attributes used to construct the model.

class SimpleParser < Wankel::SaxParser
  def on_array_start
    puts "Array start"
  end
  def on_string(string)
    puts string
  end
end

parser = SimpleParser.new
parser.parse('["string1", null, "string2"]')
# => "Array start"
# => "string1"
# => "string2"

If the model name is different than the association name you can pass the model name as an option.

belongsTo: ['village'];
// or
belongsTo: [['owner', {model: 'Village'}]];

Encoding

Viking.Collection extends Backbone.Collection, adding predicates, selections, and modifies fetch to cancel any current request if a new fetch is triggered.

Wankel.encode({"key" => "value"}) # => '{"key":"value"}'

Streaming

In addition if you want paginate your results you can also use a Viking.PaginatedCollection

A Viking.PaginatedCollection expects the response from the server to be similar to the example.

The paginated collection will have a Viking.Cursor available at collection.curosr. Any changes to the attributes page, offset, or per_page will trigger a fetch on the collection.

The cursor has several helper functions to allow you to navigate. The functions are reset, incrementPage, decrementPage, and goToPage.

output = StringIO.new
encoder = Wankel::SaxEncoder.new(output)

encoder.map_open
encoder.string("key")
encoder.number(123)
encoder.string("type")
encoder.value("value-determined-by-method")
encoder.map_close
encoder.flush

output.string # => '{"key":123,"type":"value-determined-by-method"}'