UNPKG

@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 (45 loc) 1.68 kB
'use strict'; const convertJsonPathToPointer = (dataPath) => { if (dataPath[0] === '/' || (dataPath[0] === '#' && dataPath[1] === '/')) return dataPath; if (!dataPath) return JSON_POINTER_SEPARATOR; const length = dataPath.length; let result = ''; let start = 0; let index = 0; while (index < length) { const character = dataPath[index]; if (character === JSON_PATH_SEPARATOR) { if (index > start) result += JSON_POINTER_SEPARATOR + dataPath.slice(start, index); start = index + 1; index++; } else if (character === JSON_PATH_ARRAY_INDEX_PREFIX) { if (index > start) result += JSON_POINTER_SEPARATOR + dataPath.slice(start, index); const openIndex = ++index; while (index < length && dataPath[index] !== JSON_PATH_ARRAY_INDEX_SUFFIX) index++; const arrayContent = dataPath.slice(openIndex, index); result += JSON_POINTER_SEPARATOR + (arrayContent === '' ? JSON_PATH_ARRAY_INDEX_NEW : arrayContent); if (index < length) index++; start = index; } else index++; } if (start < length) result += JSON_POINTER_SEPARATOR + dataPath.slice(start); return result || JSON_POINTER_SEPARATOR; }; const JSON_PATH_SEPARATOR = '.'; const JSON_PATH_ARRAY_INDEX_PREFIX = '['; const JSON_PATH_ARRAY_INDEX_SUFFIX = ']'; const JSON_POINTER_SEPARATOR = '/'; const JSON_PATH_ARRAY_INDEX_NEW = '-'; exports.convertJsonPathToPointer = convertJsonPathToPointer;