3.0.1 • Published 2 years ago

json-string-locator v3.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

json-string-locator

npm version npm downloads

Locate object or property position in a json string, mainly used in monaco editor, e.g. monaco.languages.registerCodeLensProvider

Install

npm i json-string-locator

Usage

import { parse, locateObject, locateProperty } from 'json-string-locator'

const ast = parse( `
  {
    "type": "foo",
    "elements": {
      "type": "bar",
      "hello": "world"
    }
  }
` )
locateObject( ast, ( object, path ) => node.type === 'bar' )
/*
  [
    {
      start: { line: 4, column: 17, offset: 40 },
      end: { line: 7, column: 6, offset: 91 },
      path: ...
    }
  ]
 */

locateProperty( ast, ( property, path ) => property.type === 'bar' )
/*
  [
    {
      start: { line: 5, column: 7, offset: 48 },
      end: { line: 5, column: 20, offset: 61 },
      path: ...
    }
  ]
 */

// information can be attached to ast, and be used in evaluate hook
const json = evaluate( ast, {
  // hook object and array
  hook( node, context ) {
    // we can modify context.value to change evaluate result
    context.value._id = 'id'
  }
} )

License

MIT © fengzilong