Useful functions when working with JSON.
Supported in modern browsers and node.
# latest stable
yarn add @stoplight/json
JSON.parse(val) but also returns parsing errors as well as full ast with line information.['paths', '/user', 'get'] -> #/paths/~1/user/get.#/paths/~1/user/get -> ['paths', '/user', 'get'].JSON.parse(val) but does not throw on invalid JSON.JSON.stringify(val) but handles circular references.x.startsWith(y) but works with strings AND arrays.lodash.startsWith(x, y) but works with strings AND arrays.parseWithPointersNote: Unlike most of the other functions, parseWithPointers is not exported from root. You must import by name.
import { parseWithPointers } from "@stoplight/json/parseWithPointers";
const result = parseWithPointers('{"foo": "bar"}');
console.log(result.data); // => the {foo: "bar"} JS object
console.log(result.pointers); // => the source map with a single "#/foo" pointer that has position info for the foo property
// basic example of getJsonPathForPosition and getLocationForJsonPath
import { getJsonPathForPosition, getLocationForJsonPath, parseWithPointers } from "@stoplight/json";
const result = parseWithPointers(`{
"hello": "world",
"address": {
"street": 123
}
}`);
const path = getJsonPathForPosition(result, { line: 3, character: 15 }); // line and character are 0-based
console.log(path); // -> ["address", "street"];
const position = getLocationForJsonPath(result, ["address"]);
console.log(position.range.start); // { line: 2, character: 13 } line and character are 0-based
console.log(position.range.end); // { line: 4, character: 3 } line and character are 0-based
feature/{name}, chore/{name}, or fix/{name} branch.yarn.yarn test.prod.yarn commit. NOTE: Commits that don't follow the conventional format will be rejected. yarn commit creates this format for you, or you can put it together manually and then do a regular git commit.git push.next branch.Removes special json pointer characters in a value. Example:
decodePointer('#/paths/~1users) => '#/paths//users'
Sets special json pointer characters in a value. Example:
encodePointer('#/paths//users) => '#/paths/~1users'
Escapes special json pointer characters in a value. Example:
encodePointer('/paths/~users) => '~1paths~1~0users'
Works on strings AND arrays, unlike native JS x.startsWith().
startsWith([1, 2], [1]) === true startsWith([2, 3], [1]) === false startsWith('123', '12') === true
Removes elems from target, matched in order, starting on the left.
Supports strings AND arrays, unlike lodash.trimStart().
trimStart([1, 2, 3], [1, 2]) === [3] trimStart([1, 2, 3], [999, 2]) === [1, 2, 3] since source[0] does not equal elems[0]
Removes special json pointer characters in a value. Example:
decodePointer('#/paths/~1users) => '#/paths//users'