jsonpointer.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var untilde = function(str) {
  2. return str.replace(/~./g, function(m) {
  3. switch (m) {
  4. case "~0":
  5. return "~";
  6. case "~1":
  7. return "/";
  8. }
  9. throw new Error("Invalid tilde escape: " + m);
  10. });
  11. }
  12. var traverse = function(obj, pointer, value) {
  13. // assert(isArray(pointer))
  14. var part = untilde(pointer.shift());
  15. if(!obj.hasOwnProperty(part)) {
  16. return null;
  17. }
  18. if(pointer.length !== 0) { // keep traversin!
  19. return traverse(obj[part], pointer, value);
  20. }
  21. // we're done
  22. if(typeof value === "undefined") {
  23. // just reading
  24. return obj[part];
  25. }
  26. // set new value, return old value
  27. var old_value = obj[part];
  28. if(value === null) {
  29. delete obj[part];
  30. } else {
  31. obj[part] = value;
  32. }
  33. return old_value;
  34. }
  35. var validate_input = function(obj, pointer) {
  36. if(typeof obj !== "object") {
  37. throw new Error("Invalid input object.");
  38. }
  39. if(pointer === "") {
  40. return [];
  41. }
  42. if(!pointer) {
  43. throw new Error("Invalid JSON pointer.");
  44. }
  45. pointer = pointer.split("/");
  46. var first = pointer.shift();
  47. if (first !== "") {
  48. throw new Error("Invalid JSON pointer.");
  49. }
  50. return pointer;
  51. }
  52. var get = function(obj, pointer) {
  53. pointer = validate_input(obj, pointer);
  54. if (pointer.length === 0) {
  55. return obj;
  56. }
  57. return traverse(obj, pointer);
  58. }
  59. var set = function(obj, pointer, value) {
  60. pointer = validate_input(obj, pointer);
  61. if (pointer.length === 0) {
  62. throw new Error("Invalid JSON pointer for set.")
  63. }
  64. return traverse(obj, pointer, value);
  65. }
  66. exports.get = get
  67. exports.set = set