Roam
XPath-like queries and in-place transformations for JSON documents.
Install
npm install --save roam
or
bower install --save roam
In the browser, Roam can be used with or without RequireJS.
The basics
Given the following JSON:
All of the following, in order of best to worst performance:
Will return:
Roam
roam({Object|String})
Construct a roam
object by wrapping a JSON object or string.
Search
Search-methods locate and return values based on a given path. Path segments are separated by periods.
Get
.get({String})
.get
traverses the document and returns an array of matching values.
roam(json).get('menu.id')
returns ["file"]
One
.one({String})
.one
immediately returns the first matched property.
roam(json).one('*menuitem.onclick')
returns "CreateNewDoc()"
Recursive queries
You can prefix any property with *
to have roam search the document (or current result
set) recursively for a matching value.
roam(json).get('*value')
returns ["File", "New", "Open", "Close"]
but
roam(json).get('menu.popup.*value')
returns ["New", "Open", "Close"]
If the first segment is a recursive query, roam will traverse the entire document. If at all possible, try to narrow down the search area before going recursive.
Arrays
You can also ask for values at specific array indexes. All of these:
Will return:
Transform
.transform({String}, {Function(value)})
.transform
traverses the document, replaces matching values with the return value of the callback,
and returns the document in its entirety.
;
Returns:
Or, a slightly sillier example:
;
Returns:
Map
.map({String}, {Function(value, index, array)})
.map
is a convenience method, equivalent to running .map
or _.map
on the returned
array from a .get
. Roam's .map
is significantly faster than JavaScript's native .map
,
and roughly equivalent to lodash's _.map
. For details on how a map function works, see
the documentation for map.
;
Returns:
Filter
.filter({String}, {Function(value, index, array)})
.filter
is a convenience method in the same vein as map, and shares its performance characteristics.
For details on how a filter function works, see the documentation for filter.
;
Returns:
A note on map and filter
Neither map nor filter support binding a custom value to this
within the callback.
Utilities
Count
.count({String})
.count
is a wrapper around .get
and will return the number of matched elements.
Has
.has({String})
.has
is a wrapper around .one
and will return true or false depending on whether a match
could be found.