alexeykuzmin.com

About simple things

jsonpointer.js

Although JSON Pointer did not become very popular since its appearance in 2011, it’s still alive and even has evolved into proposed standard.

What JSON Pointer is

It’s hard to explain it better than specification does:

JSON Pointer defines a string syntax for identifying a specific value within a JavaScript Object Notation (JSON) document.

It is similar to JSON Path, but unlike the latter JSON Pointer extracts only existing values from document and does not do any filtering or merging.

There is copy of evaluation examples from spec. Given the JSON document

1
2
3
4
5
6
7
8
9
10
11
12
{
    "foo": ["bar", "baz"],
    "": 0,
    "a/b": 1,
    "c%d": 2,
    "e^f": 3,
    "g|h": 4,
    "i\\j": 5,
    "k\"l": 6,
    " ": 7,
    "m~n": 8
}

The following strings evaluate to the accompanying values:

1
2
3
4
5
6
7
8
9
10
11
12
""       ->  whole document
"/foo"   ->  ["bar", "baz"]
"/foo/0" ->  "bar"
"/"      ->  0
"/a~1b"  ->  1
"/c%d"   ->  2
"/e^f"   ->  3
"/g|h"   ->  4
"/i\\j"  ->  5
"/k\"l"  ->  6
"/ "     ->  7
"/m~0n"  ->  8

Existing implementations

There is a bunch of JSON Pointer implementations in different languages: Erlang, Go, Perl, PHP, Python, and there are two implementations in JavaScript.

Both of JavaScript implementations work only in Node.js environment and implement something bigger than specification defines. They support methods not only for retrieving values but also for modifying JSON documents and other stuff.

jsonpointer.js

Since there was no client-side implementation of JSON Pointer in JavaScript I have created my own one – jsonpointer.js. It implements only retrieving of values defined by specification, works and all modern browsers and can be used as standalone script or AMD module. Also it works in Node.js environment and is available via npm.

Here are several examples of its usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script src="/path/to/jsonpointer.js" type="text/javascript"></script>
<script>

// XXX: Target must be a string!
var targetJSON = JSON.stringify({
  foo: {
    bar: 'foobar'
  },
  baz: [true, false]
});

jsonpointer.get(targetJSON, '/foo');  // {bar: 'foobar'}
jsonpointer.get(targetJSON, '/baz/test');  // undefined

// Partial application.
var evaluate = jsonpointer.get(targetJSON);
evaluate('/foo/bar');  // 'foobar'
evaluate('/baz');  // [true, false]

</script>

Detailed description of API can be found in project README.

Comments