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.
Background
I wrote this a few years back when I was unable to find a complete implementation of RFC 6901. It turns out that I now use the hell out of it.
Since there are a few npm modules for you to choose from, see the section on performance later in this readme; you can use your own judgement as to which package you should employ.
Install
npm install json-ptr
Use
import { JsonPointer, create } from 'json-ptr';
Example
There are many uses for JSON Pointers, here's one we encountered when we updated a public API and suddenly had clients sending two different message bodies to our APIs. This example is contrived to illustrate how we supported both new and old incoming messages:
import { JsonPointer } from 'json-ptr';
export type SupportedVersion = '1.0' | '1.1';
interface PrimaryGuestNamePointers {
name: JsonPointer;
surname: JsonPointer;
honorific: JsonPointer;
}
const versions: Record<SupportedVersion, PrimaryGuestNamePointers> = {
'1.0': {
name: JsonPointer.create('/guests/0/name'),
surname: JsonPointer.create('/guests/0/surname'),
honorific: JsonPointer.create('/guests/0/honorific'),
},
'1.1': {
name: JsonPointer.create('/primary/primaryGuest/name'),
surname: JsonPointer.create('/primary/primaryGuest/surname'),
honorific: JsonPointer.create('/primary/primaryGuest/honorific'),
}
};
interface Reservation extends Record<string, unknown> {
version?: SupportedVersion;
}
function primaryGuestName(reservation: Reservation): string {
const pointers = versions[reservation.version || '1.0'];
if (!pointers) {
throw new Error(`Unsupported reservation version: ${reservation.version}`);
}
const name = pointers.name.get(reservation) as string;
const surname = pointers.surname.get(reservation) as string;
const honorific = pointers.honorific.get(reservation) as string;
const names: string[] = [];
if (honorific) names.push(honorific);
if (name) names.push(name);
if (surname) names.push(surname);
return names.join(' ');
}
const reservationV1: Reservation = {
guests: [{
name: 'Wilbur',
surname: 'Finkle',
honorific: 'Mr.'
}, {
name: 'Wanda',
surname: 'Finkle',
honorific: 'Mrs.'
}, {
name: 'Wilma',
surname: 'Finkle',
honorific: 'Miss',
child: true,
age: 12
}]
};
const reservationV1_1: Reservation = {
version: '1.1',
primary: {
primaryGuest: {
name: 'Wilbur',
surname: 'Finkle',
honorific: 'Mr.'
},
additionalGuests: [{
name: 'Wanda',
surname: 'Finkle',
honorific: 'Mrs.'
}, {
name: 'Wilma',
surname: 'Finkle',
honorific: 'Miss',
child: true,
age: 12
}]
}
};
console.log(primaryGuestName(reservationV1));
console.log(primaryGuestName(reservationV1_1));
API Documentation
The API documentation is generated from code comments by typedoc and hosted here.
We welcome new issues if you have questions or need additional documentation.
Performance
This repository has a companion repository that makes some performance comparisons between json-ptr
, jsonpointer
and json-pointer
.
All timings are expressed as nanoseconds:
.flatten(obj)
...
MODULE | METHOD | COMPILED | SAMPLES | AVG | SLOWER
json-pointer | dict | | 10 | 464455181 |
json-ptr | flatten | | 10 | 770424039 | 65.88%
jsonpointer | n/a | | - | - |
.has(obj, pointer)
...
MODULE | METHOD | COMPILED | SAMPLES | AVG | SLOWER
json-ptr | has | compiled | 1000000 | 822 |
json-ptr | has | | 1000000 | 1747 | 112.53%
json-pointer | has | | 1000000 | 2683 | 226.4%
jsonpointer | n/a | | - | - |
.has(obj, fragmentId)
...
MODULE | METHOD | COMPILED | SAMPLES | AVG | SLOWER
json-ptr | has | compiled | 1000000 | 602 |
json-ptr | has | | 1000000 | 1664 | 176.41%
json-pointer | has | | 1000000 | 2569 | 326.74%
jsonpointer | n/a | | - | - |
.get(obj, pointer)
...
MODULE | METHOD | COMPILED | SAMPLES | AVG | SLOWER
json-ptr | get | compiled | 1000000 | 590 |
json-ptr | get | | 1000000 | 1676 | 184.07%
jsonpointer | get | compiled | 1000000 | 2102 | 256.27%
jsonpointer | get | | 1000000 | 2377 | 302.88%
json-pointer | get | | 1000000 | 2585 | 338.14%
.get(obj, fragmentId)
...
MODULE | METHOD | COMPILED | SAMPLES | AVG | SLOWER
json-ptr | get | compiled | 1000000 | 587 |
json-ptr | get | | 1000000 | 1673 | 185.01%
jsonpointer | get | compiled | 1000000 | 2105 | 258.6%
jsonpointer | get | | 1000000 | 2451 | 317.55%
json-pointer | get | | 1000000 | 2619 | 346.17%
These results have been elided because there is too much detail in the actual. Your results will vary slightly depending on the resources available where you run it.
It is important to recognize in the performance results that compiled options are faster. As a general rule, you should compile any pointers you'll be using repeatedly.
Consider this example code that queries the flickr API and prints results to the console:
'use strict';
let ptr = require('..'),
http = require('http'),
util = require('util');
let feed = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=surf,pipeline&tagmode=all&format=json&jsoncallback=processResponse';
let items = ptr.create('#/items');
let author = ptr.create('#/author');
let media = ptr.create('#/media/m');
function processResponse(json) {
let data = items.get(json);
if (data && Array.isArray(data)) {
let images = data.reduce((acc, it) => {
acc.push({
author: author.get(it),
media: media.get(it)
});
return acc;
}, []);
console.log(util.inspect(images, false, 9));
}
}
http.get(feed, function(res) {
let data = '';
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function() {
data = eval(data);
processResponse(data);
});
}).on('error', function(e) {
console.log('Got error: ' + e.message);
});
[example/real-world.js]
Tests
Tests are written using mocha and expect.js.
npm test
... or ...
mocha
Releases
License
MIT