{"name":"@humanwhocodes/momoa","version":"0.2.0","keywords":["json","ast","json tree","abstract syntax tree"],"author":{"name":"Nicholas C. Zakas"},"license":"Apache-2.0","_id":"@humanwhocodes/momoa@0.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":"cea40a1160b12cdcc3dae0b92f455c603627767e","tarball":"http://registry-npm.ywwl.com/@humanwhocodes/momoa/download/@humanwhocodes/momoa-0.2.0.tgz","fileCount":4,"integrity":"sha512-fXtbO2JLenaJtmVv96FlfN2W8ZUWZZNxwf4vYdj/V+XIBujjavTpksMxo4EpIsrmlQc8caPsKnNFayAGddlbgQ==","signatures":[{"sig":"MEUCIQCpT5rY8ctDnUUcW6nNgjqVkhSoVN61qM1JI4pwEg26KQIgZeXuCsjZJcleKkZjeYjI7HehZbjFsktJo35MKYtWyRY=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":47304,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJc/+kuCRA9TVsSAnZWagAAqFQP/ip9Btpu+gzXeSHNTRFa\noYmzkqfo3NiL3zL1XVeFWtFY4/IsMzPHR9FcJwJyKY4QX/Ss6ZOh30ZqidM/\ny+v3kTLASWfHsmIi5faJjxK8Dwcbi5Lh5k2eX+T/h3rEixw77CPspiHj5qCt\nmv8OA0dPWmaN/iDtHkCoWeQd8wBH8zBheuZ9Jy82ZHwqnS2zpA3IMq6hC1Em\nqzSAjw4v7C/Z136sdKrUEZY5Y0Nl+B94cewA5GhzJy0flinuZk44nn35vny0\nAVBs4hUxPyaC1fNjLMGv9Sq/NDlwBEO0JyU60aMCrZW/aRWHhRUniR7vhzCB\n8E34+5Nw/35g9UMGJn4m+D10P+/Wzx+IUrMhUIP257G32Yj7cyG/liF7AHhs\nJFEs65oNCJzXieVjmwCMzpM9gpBPEK+jHjX37kJqzfzGYURFqJydoQkCZ2tN\n2XNPv16S+3OlynHBI34cpLxgBVjD/CAj9jWuXCub6qIuK7IiNJ/0qSX4aftw\nAEC5Y44UDHOVNOwQATx72IuQ73fLH5pYk1hwxZ7PK8A+230yjyhDANKHaCzo\nf1TopgVGiCLPQtCuXqh0OkiGdtH+3i/GgfhAWLukYY07oryB5C+e9wEDteDI\nveNJ1W8byVuh4su9OkNFqcL172ChWmkJgscb/4m19k5NNwaVOfAA/lc5W/Vs\nX5A6\r\n=JPL3\r\n-----END PGP SIGNATURE-----\r\n","size":13236,"noattachment":false,"key":"/@humanwhocodes/momoa/-/@humanwhocodes/momoa-0.2.0.tgz"},"main":"api.js","engines":{"node":">=10.10.0"},"gitHead":"36ab68b6087eb6d54a4f2513aa1e264fa4541550","scripts":{"lint":"eslint src/*.js tests/*.js","perf":"npm run build && node tools/perf.js","test":"mocha -r esm tests/**/*.js","build":"rollup -c","regen":"npm run build && node tools/regenerate-test-data.js","pretest":"npm run build","prepublish":"npm run build"},"_npmUser":{"name":"nzakas","email":"nicholas@nczconsulting.com"},"repository":{"url":"git+https://github.com/humanwhocodes/momoa.git","type":"git"},"_npmVersion":"6.9.0","description":"JSON AST parser, tokenizer, printer, traverser.","directories":{},"_nodeVersion":"12.1.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"esm":"^3.2.25","chai":"^4.2.0","mocha":"^6.1.4","sinon":"^7.3.2","eslint":"^5.16.0","rollup":"^1.12.3","benchmark":"^2.1.4","json-to-ast":"^2.1.0","beautify-benchmark":"^0.2.4"},"_npmOperationalInternal":{"tmp":"tmp/momoa_0.2.0_1560275245788_0.7225692089540192","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":1560275246051,"_cnpm_publish_time":1560275246051,"dist-tags":{"latest":"3.3.13"}}