npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jsonpos

v4.1.2

Published

Get the textual position of a property in a JSON text

Downloads

152,895

Readme

npm version downloads build status coverage status

jsonpos

Get the text position [start, end] of a property in a JSON document.

Given the following JSON:

{
    "foo": {
        "bar": "baz"
               ^^^^^
    }
}

The position of /foo/bar (or ["foo", "bar"] if provided as an array), is:

{
    start: { line: 3, column: 16, offset: 30 },
    end: { line: 3, column: 21, offset: 35 }
}

where offset is the character offset in the JSON string.

If the property "bar" is wanted, instead of the value, set markIdentifier to true, see Simple usage.

Install

npm i jsonpos or yarn add jsonpos

Versions

  • Since v2 this is a pure ESM package, and requires Node.js >=12.20
  • Since v3 the API has changed. The dataPath option has been renamed with changed semantics.
    • Dot-based (string) dataPath is now dotPath. It's not recommended to use as it's not safe for certain characters.
      • Also, it now requires an initial .. Only the path . represents the root object.
    • Array-based dataPath is now simply path.
      • An empty object represents the root object, like in v2.
    • New slash-based (string) pointerPath is allowed, following JSON Pointer encoding.
  • Since v4:
    • json-to-ast has been replaced with json-cst which is a lot smaller.
    • getAstByObject and getAstByString was renamed getParsedByObject and getParsedByString.

Exports

The package exports the following functions:

Simple usage

Definition

jsonpos( json, options: LocationOptions ): Location

where LocationOptions is:

interface LocationOptions
    markIdentifier?: boolean;

    // Only one of the following
    dotPath: string;
    path: Array< string | number >;
    pointerPath: string;
}

and Location is:

interface Location
{
    start: Position | undefined;
    end: Position | undefined;
}

where Position is:

interface Position
{
    line: number;
    column: number;
    offset: number;
}

As dot-separated textual path:

import { jsonpos } from 'jsonpos'

const loc = jsonpos(
    '{ "foo": { "bar": "baz" } }',
    { dotPath: '.foo.bar' }
);

Note that dot-separated paths are strongly advised against.

As /-separated textual path:

import { jsonpos } from 'jsonpos'

const loc = jsonpos(
    '{ "foo": { "bar": "baz" } }',
    { pointerPath: '/foo/bar' }
);

As array path:

import { jsonpos } from 'jsonpos'

const loc = jsonpos(
    '{ "foo": { "bar": "baz" } }',
    { path: [ 'foo', 'bar' ] }
);

Advanced usage

The jsonpos function is a shorthand for getLocation( getParsedByString( json ), options )

Extract the CST (using json-cst) with getParsedByString or getParsedByObject. The result is an object of type ParsedJson:

interface ParsedJson
{
    json: any;
    jsonString: string;
    jsonDoc: CstDocument; // CstDocument is a json-cst type
}

getParsedByString

import { getParsedByString } from 'jsonpos'

const parsed = getParsedByString( '{ "foo": "bar" }' );
const { json, jsonString, jsonDoc } = parsed;

getParsedByObject

getParsedByObject will stringify the JSON using JSON.stringify(obj, null, 4) and use that to parse the CST.

import { getParsedByObject } from 'jsonpos'

const parsed = getParsedByObject( { foo: "bar" } );
const { json, jsonString, jsonDoc } = parsed;

getParsedByObject takes an optional second argument indent which can be set to something else than 4 if necessary, e.g. 2:

const parsed = getParsedByObject( { foo: "bar" }, 2 );

getLocation

The getLocation takes an parsed object as returned by getParsedByString or getParsedByObject and returns a Location object.

Definitions

getLocation( parsed: ParsedJson, options: LocationOptions ): Location

where Location is defined above.

Example

import { getParsedByString, getLocation } from 'jsonpos'

const parsed = getParsedByString( '{ "foo": "bar" }' );
const loc = getLocation( parsed, { pointerPath: '/foo' } );

getPosition

To get the position (line and column) of an offset position, use getPosition.

Definitions

getPosition( text: string, pos: number ): Position

where Position is defined above.

Example

import { getPosition } from 'jsonpos'

const text = `{
  "foo": "bar",
  "baz": 42
}`;
const loc = getPosition( text, 25 ); // 25 is start of <42>
// loc = { offset: 25, line: 3, column: 10 }

Path helpers

This package understand array paths ["foo", "bar"], dot-path ".foo.bar" and JSON Pointer paths /foo/bar. Support for dot-path is to understand older paths from Ajv. Array paths are often the most practical programatically.

parsePath

The parsePath function is what jsonpos uses to parse the path. It takes on object containing either path (an array), dotPath or pointerPath (strings), and it returns the path as an array.

parsePath( { path: [ "foo", "bar" ] } );  // -> [ "foo", "bar" ]
parsePath( { dotPath: ".foo.bar" } );     // -> [ "foo", "bar" ]
parsePath( { pointerPath: "/foo/bar" } ); // -> [ "foo", "bar" ]

JSON Pointer paths

JSON Pointer paths support the slash character (/) in a path segment, and encodes it with ~1 and ~0. encodeJsonPointerSegment and parseJsonPointerSegment does this:

encodeJsonPointerSegment( "f/o/o" ); // -> "f~1o~1o"
parseJsonPointerSegment( "f~1o~1o" ); // -> "f/o/o"

For complete paths (of segments), use encodeJsonPointerPath and parseJsonPointerPath:

encodeJsonPointerPath( [ "f/o/o", "bar" ] ); // -> "/f~1o~1o/bar"
parseJsonPointerPath( "/f~1o~1o/bar" ); // -> [ "f/o/o", "bar" ]