Last active
December 28, 2015 11:39
-
-
Save MugeSo/7494939 to your computer and use it in GitHub Desktop.
JSON Pointer [RFC6901](http://tools.ietf.org/html/rfc6901) sample implementation.
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
function parseJSONPointer(string) { | |
if (string.length < 1) { | |
return []; // root | |
} | |
if (string[0] !== '/') { | |
throw new Error('Invalid JSON Pointer syntax'); | |
} | |
return string.split('/').map(function(referenceToken){ | |
return referenceToken.replace(/~./, function(escaped) { | |
switch (escaped) { | |
case '~0': | |
return '~'; | |
case '~1': | |
return '/'; | |
} | |
throw new Error('Invalid JSON Pointer syntax'); | |
}) | |
}).slice(1); | |
} | |
function getByJSONPointer(target, pointer) { | |
function get (target, pointerArray) { | |
if (pointerArray.length === 0) { | |
return target; | |
} | |
if ( target instanceof Array && pointerArray[0] != parseInt(pointerArray[0]) || target[pointerArray[0]] === undefined) { | |
thorw new Error('Pointer references a nonexistent value'); | |
} | |
return get(target[pointerArray[0]], pointerArray.splice(1)); | |
} | |
return get(target, parseJSONPointer(pointer)); | |
} | |
function setByJSONPointer(target, pointer, value) { | |
if (pointer === '') { | |
// pointerが自身を指してるときどうしよう...... | |
// 自身に代入でもしてもらおうか | |
return value; | |
} | |
function set (target, pointerArray, value) { | |
if (pointerArray.length > 1) { | |
if ( target instanceof Array && pointerArray[0] != parseInt(pointerArray[0]) || target[pointerArray[0]] === undefined) { | |
thorw new Error('Pointer references a nonexistent value'); | |
} | |
return set(target[pointerArray[0]], pointerArray.splice(1)); | |
} | |
var key = pointerArray[0]; | |
if ( target instanceof Array ) { | |
if (key === '-') { | |
target.push(value); | |
return; | |
} | |
if (key != parseInt(key)) { | |
thorw new Error('Pointer references a nonexistent value'); | |
} | |
} | |
target[key] = value; | |
} | |
set(target, parseJSONPointer(pointer)); | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
refs RFC6901