Options
All
  • Public
  • Public/Protected
  • All
Menu

@stoplight/json

Maintainability Test Coverage

Useful functions when working with JSON.

Installation

Supported in modern browsers and node.

# latest stable
yarn add @stoplight/json

Usage

  • decycle: Remove circular references with support for an optional replacer.
  • parseWithPointers: Like JSON.parse(val) but also returns parsing errors as well as full ast with line information.
  • pathToPointer: Turns an array of path segments into a json pointer IE ['paths', '/user', 'get'] -> #/paths/~1/user/get.
  • pointerToPath: Turns a json pointer into an array of path segments IE #/paths/~1/user/get -> ['paths', '/user', 'get'].
  • safeParse: Like JSON.parse(val) but does not throw on invalid JSON.
  • safeStringify: Like JSON.stringify(val) but handles circular references.
  • startsWith: Like native JS x.startsWith(y) but works with strings AND arrays.
  • trimStart: Like lodash.startsWith(x, y) but works with strings AND arrays.
  • getJsonPathForPosition: Computes JSON path for given position.
  • getLocationForJsonPath: Retrieves location of node matching given JSON path.

Example parseWithPointers

Note: 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

Contributing

  1. Clone repo.
  2. Create / checkout feature/{name}, chore/{name}, or fix/{name} branch.
  3. Install deps: yarn.
  4. Make your changes.
  5. Run tests: yarn test.prod.
  6. Stage relevant files to git.
  7. Commit: 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.
  8. Push: git push.
  9. Open PR targeting the next branch.

Index

Functions

Const decodePointer

  • decodePointer(value: string): string
  • Removes special json pointer characters in a value. Example:

    decodePointer('#/paths/~1users) => '#/paths//users'

    Parameters

    • value: string

    Returns string

Const decodePointerFragment

  • decodePointerFragment(value: string): string
  • Removes special json pointer characters in a value. Example:

    decodePointer('#/paths/~1users) => '#/paths//users'

    Parameters

    • value: string

    Returns string

Const decycle

  • decycle<T>(value: T, replacer?: undefined | function): T
  • Type parameters

    • T

    Parameters

    • value: T
    • Optional replacer: undefined | function

    Returns T

Const encodePointer

  • encodePointer(value: string): string
  • Sets special json pointer characters in a value. Example:

    encodePointer('#/paths//users) => '#/paths/~1users'

    Parameters

    • value: string

    Returns string

Const encodePointerFragment

  • encodePointerFragment(value: Segment): Segment
  • Escapes special json pointer characters in a value. Example:

    encodePointer('/paths/~users) => '~1paths~1~0users'

    Parameters

    • value: Segment

    Returns Segment

Const getJsonPathForPosition

  • getJsonPathForPosition(__namedParameters: object, position: IPosition): undefined | (string | number)[]
  • Parameters

    • __namedParameters: object
    • position: IPosition

    Returns undefined | (string | number)[]

getLastPathSegment

  • getLastPathSegment(path: string): string

Const getLocationForJsonPath

  • getLocationForJsonPath(__namedParameters: object, path: (string | number)[], closest?: undefined | false | true): undefined | object
  • Parameters

    • __namedParameters: object
    • path: (string | number)[]
    • Default value closest: undefined | false | true = false

    Returns undefined | object

parseTree

  • parseTree<T>(text: string, errors?: IDiagnostic[], options: IParseOptions): IParserASTResult<T, Node, number[]>
  • Type parameters

    • T

    Parameters

    • text: string
    • Default value errors: IDiagnostic[] = []
    • options: IParseOptions

    Returns IParserASTResult<T, Node, number[]>

Const parseWithPointers

Const pathToPointer

  • pathToPointer(path: JsonPath): string

Const pointerToPath

  • pointerToPath(pointer: string): JsonPath

Const renameObjectKey

  • renameObjectKey(obj: object, oldKey: string, newKey: string): object
  • Parameters

    • obj: object
    • oldKey: string
    • newKey: string

    Returns object

Const safeParse

  • safeParse<T>(text: string, reviver?: undefined | function): T | undefined
  • Type parameters

    • T

    Parameters

    • text: string
    • Optional reviver: undefined | function

    Returns T | undefined

Const safeStringify

  • safeStringify(value: any, replacer?: undefined | function, space?: string | number): string
  • Parameters

    • value: any
    • Optional replacer: undefined | function
    • Optional space: string | number

    Returns string

Const startsWith

  • startsWith(source: any[] | string, val: any[] | string): boolean
  • Works on strings AND arrays, unlike native JS x.startsWith().

    startsWith([1, 2], [1]) === true startsWith([2, 3], [1]) === false startsWith('123', '12') === true

    Parameters

    • source: any[] | string
    • val: any[] | string

    Returns boolean

toPropertyPath

  • toPropertyPath(path: string): string

Const trimStart

  • trimStart(target: any[] | string, elems: any[] | string): any
  • 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]

    Parameters

    • target: any[] | string
    • elems: any[] | string

    Returns any