json-to-ast

raw JSON →
2.1.0 verified Sat Apr 25 auth: no javascript maintenance

A lightweight, zero-dependency JSON parser that produces an Abstract Syntax Tree (AST) with full location information. Version 2.1.0 supports Emoji, runs on Node >=4, and provides error messages with precise character offsets. Unlike JSON.parse, it returns a structured tree with node types like 'object', 'array', 'identifier', 'literal' and detailed 'loc' (location) data including line, column, offset, and source. Ideal for linters, formatters, code mods, and tools needing to analyze or manipulate JSON structure. Last released in 2019 with no recent updates, possibly in maintenance mode.

error Error: The 'source' option must be a string
cause Passing a non-string value (e.g., number or object) for the 'source' option.
fix
Ensure 'source' is a string: parse(json, { source: 'file.json' })
error TypeError: parse is not a function
cause Importing the module incorrectly in CJS or ESM environment.
fix
Use correct import: import parse from 'json-to-ast' or const parse = require('json-to-ast').default (for CJS with named export).
error SyntaxError: Unexpected token in JSON at position X
cause The input string is not valid JSON or has extra characters. json-to-ast throws a custom error with line/column info.
fix
Check the JSON input validity; the error message includes location details (line, column, offset).
breaking v2.0.0 renamed 'verbose' option to 'loc' and changed node type names (e.g., 'value' to 'literal', 'key' to 'identifier').
fix Use 'loc: true' instead of 'verbose: true'; update node type references to new names.
breaking v2.0.0 changed 'rawValue' to 'raw' in literal nodes.
fix Access 'raw' instead of 'rawValue' on literal nodes.
breaking v2.0.0 changed 'position' property to 'loc'.
fix Access 'loc' instead of 'position' for location data.
deprecated The package has not been updated since 2019. No future updates expected.
fix Consider alternatives like @humanwhocodes/momoa or moo/ace for active development.
gotcha Default export and named export 'parse' both exist, but some bundlers may treat default export differently.
fix Use named import for clarity: import { parse } from 'json-to-ast';
npm install json-to-ast
yarn add json-to-ast
pnpm add json-to-ast

Parses a JSON string into an AST with location info (loc: true) and source name.

import parse from 'json-to-ast';

const json = '{ "name": "Alice", "age": 30 }';
const ast = parse(json, { loc: true, source: 'example.json' });

console.log(JSON.stringify(ast, null, 2));
// Output: 
// {
//   "type": "object",
//   "children": [
//     {
//       "type": "property",
//       "key": { "type": "identifier", "value": "name", ... },
//       "value": { "type": "literal", "value": "Alice", ... }
//     },
//     {
//       "type": "property",
//       "key": { "type": "identifier", "value": "age", ... },
//       "value": { "type": "literal", "value": 30, ... }
//     }
//   ],
//   "loc": { ... }
// }