Created
April 3, 2013 10:24
-
-
Save joshleaves/5300047 to your computer and use it in GitHub Desktop.
Quick and dirty implementation of RFC 6901: http://www.rfc-editor.org/rfc/rfc6901.txt Will do RFC 6902 later...maybe...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
// Will only throw on missing leading '/' | |
*/ | |
JSON.pointer = function (object, pointer) { | |
if ('undefined' === typeof object || 'undefined' === typeof pointer || '/' === pointer) { | |
return object; | |
} | |
if ('/' !== pointer.substr(0, 1)) { | |
throw new SyntaxError('Unexpected character ' + pointer.substr(0, 1)); | |
} | |
var _path = pointer.substr(1).split('/').map(function (p, idx) { | |
if (/^[0-9]$/.test(p)) { | |
return parseInt(p); | |
} | |
return p.replace('~1', '/').replace('~0', '~'); | |
}); | |
var _object = object; | |
while (_path.length) { | |
_object = _object[_path.shift()]; | |
if ('undefined' === typeof _object) return _object; | |
} | |
return _object; | |
}; | |
/* | |
// Extending native objects prototypes is bâaad, m'kay? | |
*/ | |
Object.prototype.pointer = function (pointer) { | |
return JSON.pointer(this, pointer); | |
} | |
/* | |
// Quick test value. Complex enough? | |
*/ | |
var a = { foo: { bar: [ { hello: { world: true } } ] } }; | |
/* | |
// Let's trigger an error! | |
*/ | |
try { | |
// Invalid: Missing leading '/' | |
console.log(a.pointer('foo')); | |
} catch (e) { | |
// [SyntaxError: Unexpected character f] | |
console.log(e); | |
} | |
/* | |
// Now for some real use! | |
*/ | |
console.log(a.pointer()); | |
console.log(a.pointer('/')); | |
console.log(a.pointer('/foo')); | |
console.log(a.pointer('/foo/bar')); | |
console.log(a.pointer('/foo/bar/0')); | |
console.log(a.pointer('/foo/bar/0/hello')); | |
console.log(a.pointer('/foo/bar/0/hello/world')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment