@winglet/json
Version:
TypeScript library for safe and efficient JSON data manipulation with RFC 6901 (JSON Pointer) and RFC 6902 (JSON Patch) compliance, featuring prototype pollution protection and immutable operations
48 lines (44 loc) • 1.79 kB
JavaScript
;
var filter = require('@winglet/common-utils/filter');
var lib = require('@winglet/common-utils/lib');
var escapeSegment = require('../escape/escapeSegment.cjs');
const getJSONPointer = (root, target) => {
if (root === target)
return '/';
const pointer = getPointer(root, target);
return pointer !== null ? `/${pointer}` : null;
};
const getPointer = (root, target) => {
const stack = [[root, '']];
while (stack.length > 0) {
const [currentNode, currentPath] = stack.pop();
if (filter.isObject(currentNode)) {
if (filter.isArray(currentNode)) {
for (let i = 0, l = currentNode.length; i < l; i++) {
const value = currentNode[i];
const segments = escapeSegment.escapeSegment('' + i);
const path = currentPath ? `${currentPath}/${segments}` : segments;
if (value === target)
return path;
if (filter.isObject(value))
stack[stack.length] = [value, path];
}
}
else {
for (const key in currentNode) {
if (!lib.hasOwnProperty(currentNode, key))
continue;
const value = currentNode[key];
const segments = escapeSegment.escapeSegment(key);
const path = currentPath ? `${currentPath}/${segments}` : segments;
if (value === target)
return path;
if (filter.isObject(value))
stack[stack.length] = [value, path];
}
}
}
}
return null;
};
exports.getJSONPointer = getJSONPointer;