• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    Ruby
  • Created almost 16 years ago
  • Updated over 15 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON parser that understands cross-references and casts to typed Ruby objects. Implements JSONQuery against JSON trees and Ruby object graphs.

Siren¶ ↑

Siren is a JSON and JSONQuery interpreter for Ruby. It extends the normal functionality of JSON-to-Ruby processing with cross-references, automatic typecasting, and a succinct query language for filtering JSON and Ruby object graphs.

Installation¶ ↑

sudo gem install siren

Usage¶ ↑

As expected, Siren can be used as a basic JSON parser, though if that’s all you want you’ll be better off with more performant libraries like the json gem.

Siren.parse '[{"name": "mike"}]'
#=> [{"name"=>"mike"}]

The features listed below go beyond standard JSON and are modelled on the feature set listed in this SitePen article:

http://www.sitepen.com/blog/2008/07/16/jsonquery-data-querying-beyond-jsonpath/

Cross-references¶ ↑

Siren allows JSON objects to be given IDs, and for other objects to make references back to them from within the same document. This allows for cyclic data structures and other objects inexpressible in standard JSON.

data = Siren.parse <<-JSON
        [
            {
                "id":       "obj1",
                "name":     "mike"
            }, {
                "name":     "bob",
                "friend":   {"$ref": "obj1"}
            }
        ]
JSON

#=> [ {"name" => "mike", "id" => "obj1"},
      {"name" => "bob", "friend" => {"name" => "mike", "id" => "obj1"} } ]

So bob has a cross-reference to mike, which the parser resolves for us. Note mike is not copied but is referenced by bob:

data[0].__id__              #=> -607191558
data[1]['friend'].__id__    #=> -607191558

The general syntax for a cross-reference is {"$ref": ID_STRING}; the parser will replace this with the referenced object in the Ruby output.

Automatic typecasting¶ ↑

JSON parsers typically output hashes and arrays, these being Ruby’s closest analogues to the JavaScript types that JSON expresses. Siren allows objects to be imbued with a type attribute, which if present causes the parser to cast the object to an instance of the named type instead of a hash. Instead of hash keys, the keys in the JSON object become instance variables of the typed object. To allow the parser to use a class for casting, it must be extended using Siren::Node:

class PersonModel
  extend Siren::Node
end

data = Siren.parse <<-JSON
        {
            "type":   "person_model",
            "name":   "Jimmy",
            "age":    25
        }
JSON

#=> #<PersonModel @type="person_model", @age=25, @name="Jimmy">

JSONQuery¶ ↑

JSONQuery is a language designed for filtering and transforming JSON-like object graphs. Queries may be run against Ruby objects of any type, and may also be used as values in JSON documents to generate data during parsing. For example:

# Run a filter against an array
adults = Siren.query "$[? @.age >= 18 ]", people

# Embed the query for expansion by the parser
people = Siren.parse <<-JSON
        {
            "people": [
                {"name":  "John",   "age":  23},
                {"name":  "Paul",   "age":  21},
                {"name":  "George", "age":  12},
                {"name":  "Ringo",  "age":  17}
            ],

            "adults": {"$ref": "$.people[? @.age >= 18 ]"}
        }
JSON

As for IDs, queries are embedded using the $ref syntax. Parsing the above yields the following Ruby object:

{ "adults" => [ {"name"=>"John", "age"=>23},
                {"name"=>"Paul", "age"=>21}
              ],
  "people" => [ {"name"=>"John", "age"=>23},
                {"name"=>"Paul", "age"=>21},
                {"name"=>"George", "age"=>12},
                {"name"=>"Ringo", "age"=>17}
              ]
}

Siren supports the following sections of the JSONQuery language. A query is composed of an object selector followed by zero or more filters.

Object selectors¶ ↑

An object selector is either a valid object ID, or the special symbols $ or @.

  • An object ID is a letter followed by zero or more letters, numbers or underscores. Use of an ID produces a reference to the object with that id property, as illustrated above.

  • $ represents the root object the query is being run against, or the root of the JSON document currently being parsed.

  • @ represents the current object in a looping operation, such as a map, sort or filter.

Expressions¶ ↑

Expressions are used within filters to generate data and perform comparisons. They work in a similar fashion to JavaScript expressions, and may contain strings (enclosed in single quotes), numbers, true, false, null or other JSONQuery expressions. The following operators are supported:

  • Arithmetic: +, -, *, /, %

  • Comparison: <, <=, >, >=

  • Equality: = for equality, != for inequality

  • String matching: = for case-sensitive matching, ~ for case-insensitive

  • Logic: & for boolean AND, | boolean OR (not bitwise)

  • Subexpressions are delimited using parentheses ( and )

String matching¶ ↑

The = and ~ operators, when used with strings, perform case-sensitive and case-insensitive matching respectively. Within a string, * matches zero or more characters of any type, and ? matches a single character.

Siren.query "$[? @ = 'b*']", %w[foo bar baz]
#=> ["bar", "baz"]

Siren.query "$[? @ = 'b?']", %w[foo bar baz]
#=> []

Siren.query "$[? @ ~ 'BA?']", %w[foo bar baz]
#=> ["bar", "baz"]

Field access filter¶ ↑

A field access filter selects a named field from an object. Fields are accessed using the dot notation, or the bracket notation with an expression evaluating to a string or an integer. This filter does one of the following based on the object’s type:

  • If the object is a Hash, the value for the named key is produced.

  • If the object is an Array, the value at the given index is produced.

  • If the object has the named method, the value of that method call is returned.

  • Otherwise, the value of the named instance variable is produced.

    data = {
      "key"   => "foo",
      "name"  => { "foo" => "bar" }
    }
    
    Siren.query "$.key", data
    #=> "foo"
    
    Siren.query "$[1]", %w[foo bar whizz]
    #=> "bar"
    
    Siren.query "$.name[ $.key ]", data
    #=> "bar"
    
    Siren.query "$.size", [3,4,5]
    #=> 3
    

Fields can also be accessed recursively; the syntax ..symbol returns an array of all the values in the object with the property name symbol.

data = {"rec" => 6, "key" => {"rec" => 7}}

Siren.query "$..rec", data
#=> [6, 7]

Array slice filter¶ ↑

The array slice filter selects a subset of values from an array. The syntax is [a:b:s], where a is the start index, b the end index and s the step amount. The step may be omitted (as in [a:b]), in which case the step defaults to 1.

Siren.query "$[1:5:2]", %w[a b c d e f g h]
#=> ["b", "d", "f"]

Selection filter¶ ↑

The selection filter extracts a subset of an array using a predicate condition. Predicates are enclosed in [? ... ], and within this block the symbol @ refers to each member of the array in turn. For example:

Siren.query "$.strings[? @.length > 3]", {'strings' => %w[the quick brown fox]}
#=> ["quick", "brown"]

Siren.query "$[? @ > 2 & @ <= 5]", [9,2,7,3,8,5]
#=> [3, 5]

Selections can be made recursively by prefixing the filter with two dots (..). This will search the filtered object recursively for any properties that match the predicate expression, and return them as a flat array.

data = [
    8,2,5,7,3,
    {
        'foo' => 12,
        'bar' => 7,
        'whizz' => [9,2,6,4]
    }
]

Siren.query "$..[? @ % 4 = 0]", data
#=> [8, 4, 12]

Mapping filter¶ ↑

Mappings work like Ruby’s Enumerable#map method, producing a new array by applying some expression to the members of another. Mappings are expressed by enclosing the mapping expression in [= ... ]

Siren.query "$[= @[ 'upcase' ] ]", %w[the quick brown fox]
#=> ["THE", "QUICK", "BROWN", "FOX"]

Siren.query "$[= @.length + 2]", %w[the quick brown fox]
#=> [5, 7, 7, 5]

Just like other types of filters, mapping filters may use subqueries inside the main query:

Siren.query "$[= @[? @ > 4] ]", [ [2,9,4,3], [5,8,2], [3,6] ]
#=> [[9], [5, 8], [6]]

Siren.query "$[= @[? @ > 4][0] + @.size ]", [ [2,9,4,3], [5,8,2], [3,6] ]
#=> [13, 8, 8]

Sorting filter¶ ↑

The sorting filter returns a sorted version of the array it is operating on. The sort must contain one or more comma-separated expressions to use to compare the items in the array, and each expression must specify ascending (/) or descending (\) order. Expressions are prioritized from left to right. For example, the following sorts the people in the list in ascending order by last name, then in descending order by first name for people with the same last name:

people = Siren.parse <<-JSON
        [
            {"first": "Thom",   "last": "Yorke"},
            {"first": "Jonny",  "last": "Greenwood"},
            {"first": "Ed",     "last": "O'Brien"},
            {"first": "Colin",  "last": "Greenwood"},
            {"first": "Phil",   "last": "Selway"}
        ]
JSON

Siren.query "$[ /@.last, \\@.first ]", people

#  => [ { "last"=>"Greenwood",  "first"=>"Jonny"},
#       { "last"=>"Greenwood",  "first"=>"Colin"},
#       { "last"=>"O'Brien",    "first"=>"Ed"},
#       { "last"=>"Selway",     "first"=>"Phil"},
#       { "last"=>"Yorke",      "first"=>"Thom"} ]

License¶ ↑

(The MIT License)

Copyright © 2009 James Coglan

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

sylvester

Vector, matrix and geometry math JavaScript
JavaScript
1,141
star
2

jsclass

Implementation of the core of Ruby's object system in JavaScript.
JavaScript
509
star
3

vault

Generates safe passwords so you never need to remember them
JavaScript
471
star
4

canopy

A parser compiler for Java, JavaScript, Python, Ruby
JavaScript
418
star
5

heist

Scheme in as little Ruby and as much Scheme as possible. Supports macros, continuations, tail recursion and lazy evaluation.
Ruby
364
star
6

restore

Simple remoteStorage server written in Node.js
JavaScript
294
star
7

terminus

Capybara driver written mostly in client-side JavaScript for cross-browser automation
JavaScript
179
star
8

jit

The information manager from London
Ruby
172
star
9

fargo

Lisp with fibers for Node.js
JavaScript
157
star
10

eventful

Because Ruby's Observable never does quite what I want
Ruby
125
star
11

bake

How to make a book
XSLT
99
star
12

primer

Intelligent caching, no observers necessary
Ruby
89
star
13

nand2tetris

Solutions for http://www.nand2tetris.org/
Assembly
87
star
14

jake

Builds JavaScript projects using PackR and ERB
Ruby
78
star
15

svn2git

Ruby tool for importing existing svn projects into git and github.
Ruby
71
star
16

packr

Ruby version of Dean Edwards' Packer
Ruby
65
star
17

consent

Access control layer for ActionPack, providing a DSL for writing a firewall to sit in front of Rails controllers
Ruby
52
star
18

bluff

JavaScript implementation of topfunky's Gruff graphing library
JavaScript
42
star
19

coping

An experimental type-safe/context-aware templating library
Ruby
41
star
20

unsafe_sjr

Demo of unsafe SJR in Rails
Ruby
39
star
21

jstest

The cross-platform JavaScript test framework
JavaScript
38
star
22

node-csprng

Secure random numbers of any size in any base
JavaScript
36
star
23

wake

A build tool for web stuff
JavaScript
29
star
24

rspec-eventmachine

RSpec extensions for testing EventMachine code
Ruby
26
star
25

lisp-dojo

Dojo designed to introduce interpreter writing
Ruby
24
star
26

stickup

Tiny Scheme interpreter, suitable for use as a livecoded demo
Ruby
23
star
27

kanrens

Various implementations of microKanren
JavaScript
19
star
28

oyster

Command-line input parser that doesn't hate you
Ruby
16
star
29

action_flow

Specify request sequences in Rails
Ruby
14
star
30

tnt

Proof assistant for Typographical Number Theory
JavaScript
14
star
31

infer

Interpreter for inference rules
Ruby
13
star
32

yui

Mirror of YUI releases back to 2.2.2
JavaScript
10
star
33

3s

Small Subset of Scheme
JavaScript
9
star
34

vault-cipher

High-level authenticated encryption API used by Vault
JavaScript
9
star
35

toml

Cross-platform JavaScript TOML parser
JavaScript
9
star
36

faye-cookie-auth

Ruby
8
star
37

js-loader-examples

JavaScript
8
star
38

js-test-examples

How to run JS tests using various frameworks on different platforms
JavaScript
8
star
39

birdie

Sinatra app for making portfolio sites
Ruby
8
star
40

acceptance

Reflect on your Rails validations and generate JavaScript from them
Ruby
8
star
41

dotfiles

Vim Script
8
star
42

storeroom

Portable encrypted storage for JavaScript apps
JavaScript
8
star
43

corrode

Rust
8
star
44

lemonga.rb

just a harmless prank... for laughs
Ruby
7
star
45

nicod

Experimental logic programming system, written in Rust
Rust
7
star
46

classy_inputs

Adds type-reflecting class names to input tags in Rails
Ruby
7
star
47

remotestorage-oauth

Node.js library for getting authorization from remoteStorage servers
JavaScript
7
star
48

presentations

Slides for JavaScript talks
Ruby
7
star
49

burn-your-getters

CSS
7
star
50

has_password

Simple password-hashing abstraction for Rails models
Ruby
6
star
51

soundcloud.js

SoundCloud API wrapper for client-side JavaScript
JavaScript
6
star
52

is-sandwich

Tells you whether a thing is a sandwich
JavaScript
5
star
53

frp-irc

JavaScript
5
star
54

attr_locked

Allows you to stop ActiveRecord fields changing after an object is first created
Ruby
5
star
55

pathology

The goggles: they do nothing.
JavaScript
5
star
56

acceptance-old

A port of Ojay.Forms to Prototype, with a Rails plugin to generate client-side validation code
JavaScript
5
star
57

outcast

Music Hack Day project: broadcast your iTunes library to others over the web
JavaScript
5
star
58

york

Jekyll plugin for writing about programming
Ruby
5
star
59

jsapp

JavaScript
4
star
60

frippery

Functional streams for JavaScript
JavaScript
4
star
61

reading-and-writing

Ruby
4
star
62

mu_trumps

Cannes Midem MHD project
Ruby
4
star
63

socknet

TCP over WebSockets
JavaScript
4
star
64

jsbuild

Build tool for the JS.Package dependency system
JavaScript
4
star
65

wake-assets-ruby

Ruby HTML helper for assets managed by wake
Ruby
4
star
66

cuke-web

Browse, search and run your cukes from your browser
JavaScript
4
star
67

include_by_default

Specifies that associations should be included automatically with find() calls in ActiveRecord
Ruby
4
star
68

acts_as_uploaded

File upload plugin for Rails models
Ruby
3
star
69

toledo

JavaScript
3
star
70

pinpoint

Map location editing widget, based on Ojay and Google Maps
JavaScript
3
star
71

poker

Poker simulator for learning stats
JavaScript
3
star
72

jsmod

JavaScript
3
star
73

wake-assets-python

Python HTML helper for assets managed by wake
Python
3
star
74

reiterate

Extension for Prototype that adds syntactic sugar to Enumerable methods
JavaScript
3
star
75

jsdom-example

JavaScript
3
star
76

sequin

Generate uniformly distributed ints in any base from a bit sequence
JavaScript
3
star
77

rustlings

Rust
3
star
78

scheme-dojo

Little exercises to get familiar with Scheme and recursion
Scheme
2
star
79

holly

JavaScript and CSS dependency manager for Rails projects
Ruby
2
star
80

everything

Mini-app to display random entries from Wikipedia
Ruby
2
star
81

fowd-js-testing

Demo application with JavaScript tests
JavaScript
2
star
82

recurse-lisp-workshop

Python
2
star
83

parsing-techniques

Ruby
2
star
84

george

Like vimtutor, with additional hot beverages
Ruby
2
star
85

ruby-pci

Ruby implementations of algorithms from 'Programming Collective Intelligence'
Ruby
2
star
86

bmc

Web app collecting data on journalistic accuracy
Ruby
2
star
87

guardian-politics

Prototypal Ruby client for the Guardian Politics API
Ruby
1
star
88

rust-os

Following along with https://os.phil-opp.com/
Rust
1
star
89

jstest-phantomjs

How to run JS.Test on PhantomJS
JavaScript
1
star
90

dlt

Prototype archive format and version control system
Ruby
1
star
91

horrorshow

Experiment involving JavaScript and Ruby
Ruby
1
star
92

skwizzes

Solutions to Songkick quiz problems
Ruby
1
star
93

zairecma

Music Hack Day project, SF 2011
JavaScript
1
star
94

gramophone

Listen to neighbourhoods from the past
JavaScript
1
star
95

claw

Command-line tool for searching and opening files
Ruby
1
star
96

npm-problem

I haz a problem.
JavaScript
1
star
97

cuke-macros

Experiment wherein Cucumber features are rewritten using Scheme
Ruby
1
star
98

terminus-rails

Ruby
1
star
99

ci_search

Rails implementation of search engine from 'Programming Collective Intelligence'
Ruby
1
star