@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
46 lines (43 loc) • 1.73 kB
JavaScript
import { isObject, isArray } from '@winglet/common-utils/filter';
import { hasOwnProperty } from '@winglet/common-utils/lib';
import { escapeSegment } from '../escape/escapeSegment.mjs';
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 (isObject(currentNode)) {
if (isArray(currentNode)) {
for (let i = 0, l = currentNode.length; i < l; i++) {
const value = currentNode[i];
const segments = escapeSegment('' + i);
const path = currentPath ? `${currentPath}/${segments}` : segments;
if (value === target)
return path;
if (isObject(value))
stack[stack.length] = [value, path];
}
}
else {
for (const key in currentNode) {
if (!hasOwnProperty(currentNode, key))
continue;
const value = currentNode[key];
const segments = escapeSegment(key);
const path = currentPath ? `${currentPath}/${segments}` : segments;
if (value === target)
return path;
if (isObject(value))
stack[stack.length] = [value, path];
}
}
}
}
return null;
};
export { getJSONPointer };