Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

json-to-ast

vtrushin1.8mMIT2.1.0TypeScript support: definitely-typed

JSON AST parser

json-parser, parser, ast, json, tree

readme

JSON AST parser

NPM NPM downloads Requirements Travis-CI

Install

> npm install json-to-ast

Usage

const parse = require('json-to-ast');

const settings = {
  // Appends location information. Default is <true>
  loc: true,
  // Appends source information to node’s location. Default is <null>
  source: 'data.json'
};

parse('{"a": 1}', settings);

Output

{
  type: 'Object',
  children: [
    {
      type: 'Property',
      key: {
        type: 'Identifier',
        value: 'a',
        raw: '"a"',
        loc: {
          start: { line: 1, column: 2, offset: 1 },
          end: { line: 1, column: 5, offset: 4 },
          source: 'data.json'
        }
      },
      value: {
        type: 'Literal',
        value: 1,
        raw: '1',
        loc: {
          start: { line: 1, column: 7, offset: 6 },
          end: { line: 1, column: 8, offset: 7 },
          source: 'data.json'
        }
      },
      loc: {
        start: { line: 1, column: 2, offset: 1 },
        end: { line: 1, column: 8, offset: 7 },
        source: 'data.json'
      }
    }
  ],
  loc: {
    start: { line: 1, column: 1, offset: 0 },
    end: { line: 1, column: 9, offset: 8 },
    source: 'data.json'
  }
}

Node types

Object:

{
  type: 'Object',
  children: <Property>[],
  loc?: Object
}

Property:

{
  type: 'Property',
  key: <Identifier>,
  value: Object | Array | <Literal>,
  loc?: Object
}

Identifier:

{
  type: 'Identifier',
  value: string,
  raw: string,
  loc?: Object
}

Array:

{
  type: 'Array',
  children: (Object | Array | <Literal>)[],
  loc?: Object
}

Literal:

{
  type: 'Literal',
  value: string | number | boolean | null,
  raw: string,
  loc?: Object
}

AST explorer

Try it online on astexplorer.net

License

MIT

changelog

v2.1.0

  • Added Emoji support

v2.0.7

  • Decreased minimal NodeJS version to 4 (minimal NodeJS version 6 will be in the next major version of "json-to-ast")

v2.0.5

  • Increased minimal NodeJS version to 6

v2.0.0

  • Over-escaped identifier's value fixing (https://github.com/vtrushin/json-to-ast/issues/17)
  • Changed case for node type names
  • Changed option "verbose" parameter to "loc"
  • Changed "rawValue" to "raw"
  • Added "raw" to "Identifier" node
  • Added pretty message output

v2.0.0-alpha1.4

  • Changed error's view

v2.0.0-alpha1.3

v2.0.0-alpha1.1

  • Added tests from https://github.com/nst/JSONTestSuite
  • Changed "value" node to "literal"
  • Added "rawValue" for "literal". "value" is cast to type now
  • Changed "key" node to "identifier"
  • Renamed "position" to "loc"
  • Renamed "char" in "loc" to "offset"
  • Added "source" to "loc"

v1.2.15

  • Fixed unicode parser bug