What is json-ptr?
The json-ptr npm package provides utilities for working with JSON Pointers (RFC 6901) and JSON References (RFC 6901). It allows you to create, parse, and resolve JSON Pointers and References, making it easier to navigate and manipulate JSON data structures.
What are json-ptr's main functionalities?
Creating JSON Pointers
This feature allows you to create JSON Pointers from a string path. The example demonstrates creating a JSON Pointer for the path '/foo/bar'.
const ptr = require('json-ptr');
const pointer = ptr.create('/foo/bar');
console.log(pointer.toString()); // '/foo/bar'
Resolving JSON Pointers
This feature allows you to resolve a JSON Pointer against a JSON document to retrieve the value at the specified path. The example shows how to get the value 'baz' from the path '/foo/bar' in the given document.
const ptr = require('json-ptr');
const document = { foo: { bar: 'baz' } };
const value = ptr.get(document, '/foo/bar');
console.log(value); // 'baz'
Parsing JSON Pointers
This feature allows you to parse a JSON Pointer into its component parts. The example demonstrates parsing the pointer '/foo/bar' into an array of its segments.
const ptr = require('json-ptr');
const parsed = ptr.parse('/foo/bar');
console.log(parsed); // ['foo', 'bar']
Handling JSON References
This feature allows you to resolve JSON References within a document. The example shows how to resolve a reference to the path '#/foo/bar' and retrieve the value 'baz'.
const ptr = require('json-ptr');
const document = { foo: { bar: 'baz' }, ref: { '$ref': '#/foo/bar' } };
const value = ptr.resolve(document, document.ref);
console.log(value); // 'baz'
Other packages similar to json-ptr
jsonpointer
The jsonpointer package provides similar functionality for resolving JSON Pointers. It allows you to get and set values in a JSON document using JSON Pointers. Compared to json-ptr, jsonpointer is more focused on basic get and set operations and may not have as extensive support for JSON References.
json-ref
The json-ref package focuses on resolving JSON References within a document. It provides utilities for dereferencing JSON References and is useful for working with JSON schemas. Compared to json-ptr, json-ref is more specialized in handling JSON References and may not provide as much functionality for working with JSON Pointers.
jsonpath
The jsonpath package provides a way to query JSON documents using JSONPath expressions, which are more powerful and flexible than JSON Pointers. While jsonpath offers more advanced querying capabilities, it is not directly focused on JSON Pointers or References like json-ptr.
json-ptr
A complete implementation of JSON Pointer (RFC 6901) for nodejs and modern browsers.
Installation
node.js
$ npm install json-ptr
Tests
Tests use mocha and expect.js, so if you clone the github repository you'll need to run:
npm install
... followed by ...
npm test
... or ...
mocha -R spec
Basics
!! This document is a work in progress even though the module is considered complete. See the examples of its use for more.
JSON Pointer provides a standardized syntax for reliably referencing data within an object's structure.
Importing
nodejs
var JsonPointer = require('json-ptr')
browser
<script src="json-ptr-0.1.0.min.js"></script>
Working with Pointers
Since most non-trivial code will make use of the same pointers over and over again (after all they represent the fixed points within a larger structure), with json-ptr
you can create these pointers once and reuse them against different data items.
var manager = JsonPointer.create('/people/workplace/reporting/manager');
var director = JsonPointer.create('/people/workplace/reporting/director');
Pointers have a few simple operations:
#get
- given an origin object, returns the referenced value#set
- given an origin object and a value, sets the referenced value
And a few useful properties:
#pointer
- an RFC 6901 formatted JSON pointer#uriFragmentIdentifier
- an RFC 6901 formatted URI fragment identifier#path
- an array of property names used to descend the object graph from the origin to the referenced item
Example
This example queries the live flikr api for recent images with 'surf' and 'pipeline'. It then extracts the author and the referenced media item.
Clone the repo and run it on the command line using node example/example1.js
and you'll see the output. Of note: json-ptr
will return undefined
when any part of a pointer's path cannot be resolved, which makes this type of extraction very convenient and compact.
flikr example
var ptr = require('json-ptr')
, http = require('http')
, util = require('util')
;
var feed = "http://api.flickr.com/services/feeds/photos_public.gne?tags=surf,pipeline&tagmode=all&format=json&jsoncallback=processResponse"
, items = ptr.create("#/items")
, author = ptr.create("#/author")
, media = ptr.create("#/media/m")
;
function extractItems(it) {
return items.get(it);
}
function extractAuthorAndMedia(it, i) {
this.push({
author: author.get(it),
media : media.get(it)
});
}
function processResponse(json) {
var items = extractItems(json)
, accum = []
;
if (items && Array.isArray(items)) {
items.forEach(extractAuthorAndMedia, accum);
}
console.log( util.inspect(accum, true, 99) );
}
http.get(feed, function(res) {
console.log("Got response: " + res.statusCode);
var data = '';
res.on('data', function (chunk){
data += chunk;
});
res.on('end',function(){
eval(data);
})
}).on('error', function(e) {
console.log("Got error: " + e.message);
});