GithubHelp home page GithubHelp logo

adr-h / json-ptr Goto Github PK

View Code? Open in Web Editor NEW

This project forked from flitbit/json-ptr

0.0 1.0 0.0 137 KB

A complete implementation of JSON Pointer (RFC 6901) for nodejs and modern browsers.

License: MIT License

JavaScript 97.96% HTML 2.04%

json-ptr's Introduction

json-ptr

CircleCI

bitHound Overall Score

A complete implementation of JSON Pointer (RFC 6901) for nodejs and modern browsers.

Background

I wrote this module a couple of years ago when I was unable to find what I considered 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

// npm install json-ptr
var ptr = require('json-ptr')

browser

<script src="https://cdn.jsdelivr.net/npm/json-ptr@1/dist/json-ptr.min.js"></script>
<!-- exports an object named JsonPointer -->
<script>var ptr = JsonPointer.noConflict()</script>

Module API

Classes

  • JsonPointer : class – a convenience class for working with JSON pointers.
  • JsonReference : class – a convenience class for working with JSON references.

Functions

All example code assumes data has this structure:

var data = {
  legumes: [{
    name: 'pinto beans',
    unit: 'lbs',
    instock: 4
  }, {
    name: 'lima beans',
    unit: 'lbs',
    instock: 21
  }, {
    name: 'black eyed peas',
    unit: 'lbs',
    instock: 13
  }, {
    name: 'plit peas',
    unit: 'lbs',
    instock: 8
  }]
}

.create(pointer)

Creates an instance of the JsonPointer class.

arguments:

returns:

example:

var pointer = ptr.create('/legumes/0');
// fragmentId: #/legumes/0

.has(target,pointer)

Determins whether the specified target has a value at the pointer's path.

arguments:

returns:

  • the dereferenced value or undefined if nonexistent

.get(target,pointer)

Gets a value from the specified target object at the pointer's path

arguments:

returns:

  • the dereferenced value or undefined if nonexistent

example:

var value = ptr.get(data, '/legumes/1');
// fragmentId: #/legumes/1

.set(target, pointer, value, force)

Sets the value at the specified pointer on the target. The default behavior is to do nothing if pointer is nonexistent.

arguments:

returns:

  • The prior value at the pointer's path — therefore, undefined means the pointer's path was nonexistent.

example:

var prior = ptr.set(data, '#/legumes/1/instock', 50);

example force:

var data = {};

ptr.set(data, '#/peter/piper', 'man', true);
ptr.set(data, '#/peter/pan', 'boy', true);
ptr.set(data, '#/peter/pickle', 'dunno', true);

console.log(JSON.stringify(data, null, '  '));
{
  "peter": {
    "piper": "man",
    "pan": "boy",
    "pickle": "dunno"
  }
}

.list(target, fragmentId)

Lists all of the pointers available on the specified target.

See a discussion about cycles in the object graph later in this document if you have interest in how such is dealt with.

arguments:

  • target : object, required – the target object
  • fragmentId : boolean, optional – indicates whether fragment identifiers should be listed instead of pointers

returns:

  • an array of pointer-value pairs

example:

var list = ptr.list(data);
[ ...
  {
    "pointer": "/legumes/2/unit",
    "value": "ea"
  },
  {
    "pointer": "/legumes/2/instock",
    "value": 9340
  },
  {
    "pointer": "/legumes/3/name",
    "value": "plit peas"
  },
  {
    "pointer": "/legumes/3/unit",
    "value": "lbs"
  },
  {
    "pointer": "/legumes/3/instock",
    "value": 8
  }
]

fragmentId example:

var list = ptr.list(data, true);
[ ...
  {
    "fragmentId": "#/legumes/2/unit",
    "value": "ea"
  },
  {
    "fragmentId": "#/legumes/2/instock",
    "value": 9340
  },
  {
    "fragmentId": "#/legumes/3/name",
    "value": "plit peas"
  },
  {
    "fragmentId": "#/legumes/3/unit",
    "value": "lbs"
  },
  {
    "fragmentId": "#/legumes/3/instock",
    "value": 8
  }
]

.flatten(target, fragmentId)

Flattens an object graph (the target) into a single-level object of pointer-value pairs.

arguments:

  • target : object, required – the target object
  • fragmentId : boolean, optional – indicates whether fragment identifiers should be listed instead of pointers

returns:

  • a flattened object of property-value pairs as properties.

example:

var obj = ptr.flatten(data, true);
{ ...
  "#/legumes/1/name": "lima beans",
  "#/legumes/1/unit": "lbs",
  "#/legumes/1/instock": 21,
  "#/legumes/2/name": "black eyed peas",
  "#/legumes/2/unit": "ea",
  "#/legumes/2/instock": 9340,
  "#/legumes/3/name": "plit peas",
  "#/legumes/3/unit": "lbs",
  "#/legumes/3/instock": 8
}

.map(target, fragmentId)

Flattens an object graph (the target) into a Map object.

arguments:

  • target : object, required – the target object
  • fragmentId : boolean, optional – indicates whether fragment identifiers should be listed instead of pointers

returns:

  • a Map object containing key-value pairs where keys are pointers.

example:

var map = ptr.map(data, true);

for (let it of map) {
  console.log(JSON.stringify(it, null, '  '));
}
...
["#/legumes/0/name", "pinto beans"]
["#/legumes/0/unit", "lbs"]
["#/legumes/0/instock", 4 ]
["#/legumes/1/name", "lima beans"]
["#/legumes/1/unit", "lbs"]
["#/legumes/1/instock", 21 ]
["#/legumes/2/name", "black eyed peas"]
["#/legumes/2/unit", "ea"]
["#/legumes/2/instock", 9340 ]
["#/legumes/3/name", "plit peas"]
["#/legumes/3/unit", "lbs"]
["#/legumes/3/instock", 8 ]

.decode(pointer)

Decodes the specified pointer.

arguments:

returns:

  • An array of path segments used as indexers to descend from a root/target object to a referenced value.

example:

var path = ptr.decode('#/legumes/1/instock');
[ "legumes", "1", "instock" ]

.decodePointer(pointer)

Decodes the specified pointer.

arguments:

returns:

  • An array of path segments used as indexers to descend from a root/target object to a referenced value.

example:

var path = ptr.decodePointer('/people/wilbur dongleworth/age');
[ "people", "wilbur dongleworth", "age" ]

.encodePointer(path)

Encodes the specified path as a JSON pointer in JSON string representation.

arguments:

  • path : Array, required – an array of path segments

returns:

example:

var path = ptr.encodePointer(['people', 'wilbur dongleworth', 'age']);
"/people/wilbur dongleworth/age"

.decodeUriFragmentIdentifier(pointer)

Decodes the specified pointer.

arguments:

returns:

  • An array of path segments used as indexers to descend from a root/target object to a referenced value.

example:

var path = ptr.decodePointer('#/people/wilbur%20dongleworth/age');
[ "people", "wilbur dongleworth", "age" ]

.encodeUriFragmentIdentifier(path)

Encodes the specified path as a JSON pointer in URI fragment identifier representation.

arguments:

  • path : Array, required - an array of path segments

returns:

example:

var path = ptr.encodePointer(['people', 'wilbur dongleworth', 'age']);
"#/people/wilbur%20dongleworth/age"

.noConflict()

Restores a conflicting JsonPointer variable in the global/root namespace (not necessary in node, but useful in browsers).

example:

  <!-- ur codez -->
  <script src="/json-ptr-0.3.0.min.js"></script>
  <script>
  // At this point, JsonPointer is the json-ptr module
  var ptr = JsonPointer.noConflict();
  // and now it is restored to whatever it was before the json-ptr import.
  </script>

JsonPointer Class

Encapsulates pointer related operations for a specified pointer.

properties:

methods:

.has(target)

Determins whether the specified target has a value at the pointer's path.

.get(target)

Looks up the specified target's value at the pointer's path if such exists; otherwise undefined.

.set(target, value, force)

Sets the specified target's value at the pointer's path, if such exists.If force is specified (truthy), missing path segments are created and the value is always set at the pointer's path.

arguments:

result:

  • The prior value at the pointer's path — therefore, undefined means the pointer's path was nonexistent.

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';

var ptr = require('..'),
  http = require('http'),
  util = require('util');

// A flickr feed, tags surf,pipeline
var feed = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=surf,pipeline&tagmode=all&format=json&jsoncallback=processResponse';

// Compile/prepare the pointers...
var items = ptr.create('#/items');
var author = ptr.create('#/author');
var media = ptr.create('#/media/m');

function processResponse(json) {
  var data = items.get(json);

  if (data && Array.isArray(data)) {
    let images = data.reduce((acc, it) => {
      // Using the prepared pointers to select parts...
      acc.push({
        author: author.get(it),
        media: media.get(it)
      });
      return acc;
    }, []);
    console.log(util.inspect(images, false, 9));
  }
}

http.get(feed, function(res) {
  var data = '';

  res.on('data', function(chunk) {
    data += chunk;
  });

  res.on('end', function() {
    // result is formatted as jsonp... this is for illustration only.
    data = eval(data); // eslint-disable-line no-eval
    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

  • 2016-07-26 — 1.0.1

    • Fixed a problem with the Babel configuration
  • 2016-01-12 — 1.0.0

    • Rolled major version to 1 to reflect breaking change in .list(obj, fragmentId).
  • 2016-01-02 — 0.3.0

    • Retooled for node 4+
    • Better compiled pointers
    • Unrolled recursive .list function
    • Added .map function
    • Fully linted
    • Lots more tests and examples.
    • Documented many previously undocumented features.
  • 2014-10-21 — 0.2.0 Added #list function to enumerate all properties in a graph, producing fragmentId/value pairs.

License

MIT

json-ptr's People

Contributors

adr-h avatar cehoffman avatar mortonfox avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.