{"name":"@humanwhocodes/momoa","version":"3.2.0","keywords":["json","ast","json tree","abstract syntax tree"],"author":{"name":"Nicholas C. Zakas"},"license":"Apache-2.0","_id":"@humanwhocodes/momoa@3.2.0","maintainers":[{"name":"nzakas","email":"nicholas@nczconsulting.com"}],"homepage":"https://github.com/humanwhocodes/momoa#readme","bugs":{"url":"https://github.com/humanwhocodes/momoa/issues"},"dist":{"shasum":"42a8f773b176373e7a7876d58925fd3a91a0952f","tarball":"http://registry-npm.ywwl.com/@humanwhocodes/momoa/download/@humanwhocodes/momoa-3.2.0.tgz","fileCount":6,"integrity":"sha512-xvLEGSmd8qxcqlKFnTxdnmqQFsYGC4GhpuhHgdFoZBV9zxvmSlTuasj2D3vei3IsBGmjP/ITwPFejNAG/w+jsw==","signatures":[{"sig":"MEUCIQCv+rrESQBDCr923pI21M+dCbCQ6f4M8EqnmrOLvJvWfQIgMZG5/UmUNsDoMGw2VH7BU3DN+v2gLzxCGgeXRWiHdfE=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":186587,"size":39471,"noattachment":false,"key":"/@humanwhocodes/momoa/-/@humanwhocodes/momoa-3.2.0.tgz"},"main":"dist/momoa.cjs","type":"module","types":"dist/momoa.d.ts","module":"dist/momoa.js","engines":{"node":">=18"},"exports":{"import":"./dist/momoa.js","require":"./dist/momoa.cjs"},"gitHead":"fd0dc3fd381194eb920b0afc06c4fe4c741d0453","scripts":{"lint":"eslint *.js src/*.js tests/*.js","perf":"npm run build && node tools/perf.js","test":"mocha tests/**/*.js","build":"rollup -c && npm run fixup && tsc --project tsconfig.build.json && rollup -c rollup.types.js","fixup":"node tools/strip-typedef-aliases.js","regen":"npm run build && node tools/regenerate-test-data.js","prepare":"npm run build","pretest":"npm run build"},"_npmUser":{"name":"nzakas","email":"nicholas@nczconsulting.com"},"repository":{"url":"git+https://github.com/humanwhocodes/momoa.git","type":"git"},"_npmVersion":"10.7.0","description":"JSON AST parser, tokenizer, printer, traverser.","directories":{},"_nodeVersion":"20.15.1","_hasShrinkwrap":false,"devDependencies":{"esm":"3.2.25","chai":"^4.3.7","json5":"^2.2.3","mocha":"^10.2.0","sinon":"^15.0.1","eslint":"8.36.0","rollup":"^4.19.0","benchmark":"2.1.4","typescript":"^4.9.5","json-to-ast":"2.1.0","npm-run-all":"^4.1.5","rollup-plugin-dts":"^6.1.1","beautify-benchmark":"0.2.4","rollup-plugin-copy":"^3.4.0"},"_npmOperationalInternal":{"tmp":"tmp/momoa_3.2.0_1721683515604_0.03922412532838804","host":"s3://npm-registry-packages"},"readme":"# Momoa JSON\n\nby [Nicholas C. Zakas](https://humanwhocodes.com)\n\nIf you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).\n\n## About\n\nMomoa is a general purpose JSON utility toolkit, containing:\n\n* A **tokenizer** that allows you to separate a JSON string into its component parts.\n* A ECMA-404 compliant **parser** that produces an abstract syntax tree (AST) representing everything inside of a JSON string.\n* A **traverser** that visits an AST produced by the parser in order.\n* A **printer** that can convert an AST produced by the parser back into a valid JSON string.\n\n## Background\n\nJavaScript defines the `JSON` object with methods for both parsing strings into objects and converting objects into JSON-formatted strings. In most cases, this is exactly what you need and should use without question. However, these methods aren't useful for more fine-grained analysis of JSON structures. For instance, you'll never know if a JSON object contains two properties with the same names because `JSON.parse()` will ignore the first one and return the value of the second. A tool like Momoa comes in handy when you want to know not just the result of JSON parsing, but exactly what is contained in the original JSON string.\n\n## Usage\n\n### Node.js\n\nInstall using [npm][npm] or [yarn][yarn]:\n\n```\nnpm install @humanwhocodes/momoa\n\n# or\n\nyarn add @humanwhocodes/momoa\n```\n\nImport into your Node.js project:\n\n```js\n// CommonJS\nconst { parse } = require(\"@humanwhocodes/momoa\");\n\n// ESM\nimport { parse } from \"@humanwhocodes/momoa\";\n```\n\n### Deno\n\nImport into your Deno project:\n\n```js\nimport { parse } from \"https://cdn.skypack.dev/@humanwhocodes/momoa?dts\";\n```\n\n### Bun\n\nInstall using this command:\n\n```\nbun add @humanwhocodes/momoa\n```\n\nImport into your Bun project:\n\n```js\nimport { parse } from \"@humanwhocodes/momoa\";\n```\n\n### Browser\n\nIt's recommended to import the minified version to save bandwidth:\n\n```js\nimport { parse } from \"https://cdn.skypack.dev/@humanwhocodes/momoa?min\";\n```\n\nHowever, you can also import the unminified version for debugging purposes:\n\n```js\nimport { parse } from \"https://cdn.skypack.dev/@humanwhocodes/momoa\";\n```\n\n## API\n\n### Parsing \n\nTo parse a JSON string into an AST, use the `parse()` function:\n\n```js\nconst { parse } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\n```\n\nThe `parse()` function accepts a second argument, which is an options object that may contain one or more of the following properties:\n\n* `mode` (default: `\"json\"`) - specify the parsing mode. Possible options are `\"json\"`, `\"jsonc\"` (JSON with comments), and `\"json5\"`.\n* `ranges` (default: `false`) - set to `true` if you want each node to also have a `range` property, which is an array containing the start and stop index for the syntax within the source string.\n* `tokens` - set to `true` to return a `tokens` property on the root node containing all of the tokens used to parse the code. If `mode` is `\"jsonc\"` or `\"json5\"`, then the tokens include comment tokens.\n* `allowTrailingCommas` - set to `true` to allow trailing commas in arrays and objects in `\"json\"` and `\"jsonc\"` modes. This option is ignored in JSON5 mode.\n\nHere's an example of passing options:\n\n```js\nconst { parse } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string, {\n    mode: \"jsonc\",\n    ranges: true,\n    tokens: true\n});\n\n// root now has a range array\nconsole.dir(ast.range);\n\n// root now has a tokens array\nconsole.dir(ast.tokens);\n```\n\n### Tokenizing \n\nTo produce JSON tokens from a string, use the `tokenize()` function:\n\n```js\nconst { tokenize } = require(\"@humanwhocodes/momoa\");\nconst json = \"{\\\"foo\\\":\\\"bar\\\"}\";\n\nfor (const token of tokenize(json)) {\n    console.log(\"Token type is\", token.type);\n\n    const start = token.loc.start.offset;\n    const end = token.loc.end.offset;\n    console.log(\"Token value is\", json.slice(start, end));\n}\n```\n\nThe `tokenize()` function accepts a second parameter, which is an options object that may contain one or more of the following properties:\n\n* `mode` (default: `\"json\"`) - specify the parsing mode. Possible options are `\"json\"`, `\"jsonc\"` (JSON with comments), and `\"json5\"`.\n* `ranges` (default: `false`) - set to `true` if you want each token to also have a `range` property, which is an array containing the start and stop index for the syntax within the source string.\n\n### Traversing\n\nThere are two ways to traverse an AST: iteration and traditional traversal.\n\n#### Iterating\n\nIteration uses a generator function to create an iterator over the AST:\n\n```js\nconst { parse, iterator } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\n\nfor (const { node, parent, phase } of iterator(ast)) {\n    console.log(node.type);\n    console.log(phase); // \"enter\" or \"exit\"\n}\n```\n\nEach step of the iterator returns an object with three properties:\n\n1. `node` - the node that the traversal is currently visiting\n1. `parent` - the parent node of `node`\n1. `phase` - a string indicating the phase of traversal (`\"enter\"` when first visiting the node, `\"exit\"` when leaving the node)\n\nYou can also filter the iterator by passing in a filter function. For instance, if you only want steps to be returned in the `\"enter\"` phase, you can do this:\n\n```js\nconst { parse, iterator } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\n\nfor (const { node } of iterator(ast, ({ phase }) => phase === \"enter\")) {\n    console.log(node.type);\n}\n```\n\n#### Traversing\n\nTraversing uses a function that accepts an object with `enter` and `exit` properties:\n\n```js\nconst { parse, traverse } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\n\ntraverse(ast, {\n    enter(node, parent) {\n        console.log(\"Entering\", node.type);\n    },\n    exit(node, parent) {\n        console.log(\"Exiting\", node.type);\n    }\n});\n```\n\n## Evaluating\n\nTo convert an AST into the JavaScript value it represents, use the `evaluate()` function:\n\n```js\nconst { parse, evaluate } = require(\"@humanwhocodes/momoa\");\n\n// same as JSON.parse(some_json_string)\nconst ast = parse(some_json_string);\nconst value = evaluate(ast);\n```\n\nIn this example, `value` is the same result you would get from calling `JSON.parse(some_json_string)` (`ast` is the intermediate format representing the syntax).\n\n### Printing\n\nTo convert an AST back into a JSON string, use the `print()` function:\n\n```js\nconst { parse, print } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\nconst text = print(ast);\n```\n\n**Note:** The printed AST will not produce the same result as the original JSON text as the AST does not preserve whitespace.\n\nYou can modify the output of the `print()` function by passing in an object with an `indent` option specifying the number of spaces to use for indentation. When the `indent` option is passed, the text produced will automatically have newlines insert after each `{`, `}`, `[`, `]`, and `,` characters.\n\n```js\nconst { parse, print } = require(\"@humanwhocodes/momoa\");\n\nconst ast = parse(some_json_string);\nconst text = print(ast, { indent: 4 });\n```\n\n### Visitor Keys\n\nMomoa also exports a map of traversable properties in AST nodes that is helpful if you'd like to traverse an AST manually. This is a map where the keys are the `type` property of each AST node and the values are an array of property names to traverse.\n\n```js\nconst { visitorKeys } = require(\"@humanwhocodes/momoa\");\n\nconsole.log(visitorKeys.get(\"Document\")); // \"body\"\n```\n\n## Development\n\nTo work on Momoa, you'll need:\n\n* [Git](https://git-scm.com/)\n* [Node.js](https://nodejs.org)\n\nMake sure both are installed by visiting the links and following the instructions to install.\n\nNow you're ready to clone the repository:\n\n```bash\ngit clone https://github.com/humanwhocodes/momoa.git\n```\n\nThen, enter the directory and install the dependencies:\n\n```bash\ncd momoa/js\nnpm install\n```\n\nAfter that, you can run the tests via:\n\n```bash\nnpm test\n```\n\n**Note:** Momoa builds itself into a single file for deployment. The `npm test` command automatically rebuilds Momoa into that single file whenever it is run. If you are testing in a different way, then you may need to manually rebuild using the `npm run build` command.\n\n## Acknowledgements\n\nThis project takes inspiration (but not code) from a number of other projects:\n\n* [`Esprima`](https://esprima.org) inspired the package interface and AST format.\n* [`json-to-ast`](https://github.com/vtrushin/json-to-ast) inspired the AST format.\n* [`parseJson.js`](https://gist.github.com/rgrove/5cc64db4b9ae8c946401b230ba9d2451) inspired me by showing writing a parser isn't all that hard.\n\n## License\n\nApache 2.0\n\n## Frequently Asked Questions\n\n### What does \"Momoa\" even mean?\n\nMomoa is the last name of American actor [Jason Momoa](https://en.wikipedia.org/wiki/Jason_Momoa). Because \"JSON\" is pronounced \"Jason\", I wanted a name that played off of this fact. The most obvious choice would have been something related to [Jason and the Argonauts](https://en.wikipedia.org/wiki/Jason_and_the_Argonauts_(1963_film)), as this movie is referenced in the [JSON specification](https://ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) directly. However, both \"Argo\" and \"Argonaut\" were already used for open source projects. When I did a search for \"Jason\" online, Jason Momoa was the first result that came up. He always plays badass characters so it seemed to fit.\n\n### Why support comments in JSON?\n\nThere are a number of programs that allow C-style comments in JSON files, most notably, configuration files for [Visual Studio Code](https://code.visualstudio.com). As there seems to be a need for this functionality, I decided to add it out-of-the-box.\n\n[npm]: https://npmjs.com/\n[yarn]: https://yarnpkg.com/\n","publish_time":1721683515934,"_cnpm_publish_time":1721683515934,"dist-tags":{"latest":"3.3.13"}}