Skip to content

Commit

Permalink
Support 'null' as a valid value to set as a property, use 'undefined'…
Browse files Browse the repository at this point in the history
… for undefined props (#27)
  • Loading branch information
mtharrison authored and marcbachmann committed May 19, 2016
1 parent bc72857 commit 9b25b5c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
4 changes: 2 additions & 2 deletions jsonpointer.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function setter (obj, pointer, value) {
}

var oldValue = obj[part]
if (value === null) delete obj[part]
if (value === undefined) delete obj[part]
else obj[part] = value
return oldValue
}
Expand All @@ -65,7 +65,7 @@ function get (obj, pointer) {
for (var p = 1; p < len;) {
obj = obj[untilde(pointer[p++])]
if (len === p) return obj
if (typeof obj !== 'object') return null
if (typeof obj !== 'object') return undefined
}
}

Expand Down
15 changes: 15 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,25 @@ assert.equal(jsonpointer.get(obj, '/d/e/0/a'), 4)
assert.equal(jsonpointer.get(obj, '/d/e/1/b'), 5)
assert.equal(jsonpointer.get(obj, '/d/e/2/c'), 6)

// can set `null` as a value
assert.equal(jsonpointer.set(obj, '/f/g/h/foo/0', null), 'test')
assert.strictEqual(jsonpointer.get(obj, '/f/g/h/foo/0'), null)
assert.equal(jsonpointer.set(obj, '/b/c', null), 3)
assert.strictEqual(jsonpointer.get(obj, '/b/c'), null)

assert.equal(jsonpointer.get(obj, ''), obj)
assert.throws(function () { jsonpointer.get(obj, 'a') }, validateError)
assert.throws(function () { jsonpointer.get(obj, 'a/') }, validateError)

// can unset values with `undefined`
jsonpointer.set(obj, '/a', undefined)
assert.strictEqual(jsonpointer.get(obj, '/a'), undefined)
jsonpointer.set(obj, '/d/e/1', undefined)
assert.strictEqual(jsonpointer.get(obj, '/d/e/1'), undefined)

// returns `undefined` when path extends beyond any existing objects
assert.strictEqual(jsonpointer.get(obj, '/x/y/z'), undefined)

function validateError (err) {
if ((err instanceof Error) && /Invalid JSON pointer/.test(err.message)) {
return true
Expand Down

0 comments on commit 9b25b5c

Please sign in to comment.