From ea7d1ce0a6daa5dd1c78a83caf9f2da6738f40a4 Mon Sep 17 00:00:00 2001 From: Joe Hildebrand Date: Sun, 20 Jan 2013 16:03:01 -0500 Subject: [PATCH] Return null instead of throwing an exception when the pointer is valid, but the doc does not contain the given value. --- README.md | 1 + jsonpointer.js | 5 ++--- test.js | 17 +++++++---------- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index bcfdb1a..9c59e46 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ This is an implementation of [JSON Pointer](http://tools.ietf.org/html/draft-iet var three = jsonpointer.get(obj, "/qux/0"); var four = jsonpointer.get(obj, "/qux/1"); var five = jsonpointer.get(obj, "/qux/2"); + var notfound = jsonpointer.get(obj, "/quo"); // returns null jsonpointer.set(obj, "/foo", 6); // obj.foo = 6; diff --git a/jsonpointer.js b/jsonpointer.js index 3f53026..7b53be3 100644 --- a/jsonpointer.js +++ b/jsonpointer.js @@ -15,9 +15,8 @@ var untilde = function(str) { var traverse = function(obj, pointer, value) { // assert(isArray(pointer)) var part = untilde(pointer.shift()); - if(typeof obj[part] === "undefined") { - throw("Value for pointer '" + pointer + "' not found."); - return; + if(!obj.hasOwnProperty(part)) { + return null; } if(pointer.length !== 0) { // keep traversin! return traverse(obj[part], pointer, value); diff --git a/test.js b/test.js index cdb8ec5..31e492c 100644 --- a/test.js +++ b/test.js @@ -33,7 +33,10 @@ assert.equal(jsonpointer.get(obj, "/d/e/2/c"), 6); assert.equal(jsonpointer.get(obj, ""), obj); assert.throws(function() { - assert.equal(jsonpointer.get(obj, "a"), 3); + jsonpointer.get(obj, "a"); +}); +assert.throws(function() { + jsonpointer.get(obj, "a/"); }); var complexKeys = { @@ -51,19 +54,13 @@ assert.equal(jsonpointer.get(complexKeys, "/a~1b/c"), 1); assert.equal(jsonpointer.get(complexKeys, "/d/e~1f"), 2); assert.equal(jsonpointer.get(complexKeys, "/~01"), 3); assert.equal(jsonpointer.get(complexKeys, "/01"), 4); -assert.throws(function() { - assert.equal(jsonpointer.get(complexKeys, "/a/b/c"), 1); -}); -assert.throws(function() { - assert.equal(jsonpointer.get(complexKeys, "/~1"), 3); -}); +assert.equal(jsonpointer.get(complexKeys, "/a/b/c"), null); +assert.equal(jsonpointer.get(complexKeys, "/~1"), null); // draft-ietf-appsawg-json-pointer-08 has special array rules var ary = [ "zero", "one", "two" ]; +assert.equal(jsonpointer.get(ary, "/01"), null); -assert.throws(function() { - assert.equal(jsonpointer.get(ary, "/01"), "one"); -}); //assert.equal(jsonpointer.set(ary, "/-", "three"), null); //assert.equal(ary[3], "three");