Debian Codegraph @

debian/build_modules/@humanwhocodes/momoa/README.md

raw
1 # Momoa JSON
2
3 by [Nicholas C. Zakas](https://humanwhocodes.com)
4
5 If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate).
6
7 ## About
8
9 Momoa is a general purpose JSON utility toolkit, containing:
10
11 * A **tokenizer** that allows you to separate a JSON string into its component parts.
12 * A ECMA-404 compliant **parser** that produces an abstract syntax tree (AST) representing everything inside of a JSON string.
13 * A **traverser** that visits an AST produced by the parser in order.
14 * A **printer** that can convert an AST produced by the parser back into a valid JSON string.
15
16 ## Background
17
18 JavaScript 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.
19
20 ## Installation
21
22 You can install Momoa using npm or Yarn:
23
24 ```bash
25 npm install @humanwhocodes/momoa --save
26
27 # or
28
29 yarn add @humanwhocodes/momoa
30 ```
31
32 ## Usage
33
34 ### Parsing
35
36 To parse a JSON string into an AST, use the `parse()` function:
37
38 ```js
39 const { parse } = require("@humanwhocodes/momoa");
40
41 const ast = parse(some_json_string);
42 ```
43
44 The `parse()` function accepts a second argument, which is an options object that may contain one or more of the following properties:
45
46 * `comments` - set to `true` if you want to parse C-style line and block comments inside of JSON.
47 * `ranges` - 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. If `tokens` is also `true`, then the tokens will also have `range` properties.
48 * `tokens` - set to `true` to return a `tokens` property on the root node containing all of the tokens used to parse the code. If `comments` is also `true`, then the tokens include comment tokens.
49
50 Here's an example of passing options:
51
52 ```js
53 const { parse } = require("@humanwhocodes/momoa");
54
55 const ast = parse(some_json_string, { tokens: true });
56
57 // root now has a tokens array
58 console.dir(ast.tokens);
59 ```
60
61 ### Tokenizing
62
63 To produce JSON tokens from a string, use the `tokenize()` function:
64
65 ```js
66 const { tokenize } = require("@humanwhocodes/momoa");
67
68 for (const token of tokenize(some_json_string)) {
69 console.log(token.type);
70 console.log(token.value);
71 }
72 ```
73
74 The `tokenize()` function accepts a second parameter, which is an options object that may contain one or more of the following properties:
75
76 * `comments` - set to `true` if you want to tokenize C-style line and block comments inside of JSON.
77 * `ranges` - 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.
78
79 ### Traversing
80
81 There are two ways to traverse an AST: iteration and traditional traversal.
82
83 #### Iterating
84
85 Iteration uses a generator function to create an iterator over the AST:
86
87 ```js
88 const { parse, iterator } = require("@humanwhocodes/momoa");
89
90 const ast = parse(some_json_string);
91
92 for (const { node, parent, phase } of iterator(ast)) {
93 console.log(node.type);
94 console.log(phase); // "enter" or "exit"
95 }
96 ```
97
98 Each step of the iterator returns an object with three properties:
99
100 1. `node` - the node that the traversal is currently visiting
101 1. `parent` - the parent node of `node`
102 1. `phase` - a string indicating the phase of traversal (`"enter"` when first visiting the node, `"exit"` when leaving the node)
103
104 You 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:
105
106 ```js
107 const { parse, iterator } = require("@humanwhocodes/momoa");
108
109 const ast = parse(some_json_string);
110
111 for (const { node } of iterator(ast, ({ phase }) => phase === "enter")) {
112 console.log(node.type);
113 }
114 ```
115
116 #### Traversing
117
118 Traversing uses a function that accepts an object with `enter` and `exit` properties:
119
120 ```js
121 const { parse, traverse } = require("@humanwhocodes/momoa");
122
123 const ast = parse(some_json_string);
124
125 traverse(ast, {
126 enter(node, parent) {
127 console.log("Entering", node.type);
128 },
129 exit(node, parent) {
130 console.log("Exiting", node.type);
131 }
132 });
133 ```
134
135 ## Evaluating
136
137 To convert an AST into the JavaScript value it represents, use the `evaluate()` function:
138
139 ```js
140 const { parse, evaluate } = require("@humanwhocodes/momoa");
141
142 // same as JSON.parse(some_json_string)
143 const ast = parse(some_json_string);
144 const value = evaluate(ast);
145 ```
146
147 In 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).
148
149 ### Printing
150
151 To convert an AST back into a JSON string, use the `print()` function:
152
153 ```js
154 const { parse, print } = require("@humanwhocodes/momoa");
155
156 const ast = parse(some_json_string);
157 const text = print(ast);
158 ```
159
160 **Note:** The printed AST will not produce the same result as the original JSON text as the AST does not preserve whitespace.
161
162 You 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.
163
164 ```js
165 const { parse, print } = require("@humanwhocodes/momoa");
166
167 const ast = parse(some_json_string);
168 const text = print(ast, { indent: 4 });
169 ```
170
171 ## Development
172
173 To work on Momoa, you'll need:
174
175 * [Git](https://git-scm.com/)
176 * [Node.js](https://nodejs.org)
177
178 The first step is to clone the repository:
179
180 ```bash
181 git clone https://github.com/humanwhocodes/momoa.git
182 ```
183
184 Then, enter the directory and install the dependencies:
185
186 ```bash
187 cd momoa
188 npm install
189 ```
190
191 After that, you can run the tests via:
192
193 ```bash
194 npm test
195 ```
196
197 **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.
198
199 ## Acknowledgements
200
201 This project takes inspiration (but not code) from a number of other projects:
202
203 * [`Esprima`](https://esprima.org) inspired the package interface and AST format.
204 * [`json-to-ast`](https://github.com/vtrushin/json-to-ast) inspired the AST format.
205 * [`parseJson.js`](https://gist.github.com/rgrove/5cc64db4b9ae8c946401b230ba9d2451) inspired me by showing writing a parser isn't all that hard.
206
207 ## License
208
209 Apache 2.0
210
211 ## Frequently Asked Questions
212
213 ### What does "Momoa" even mean?
214
215 Momoa 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.
216
217 ### Why support comments in JSON?
218
219 There 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.
220
221 ### Why are the source files in ESM and the test files are in CommonJS?
222
223 Unfortunately, Node.js still doesn't natively support ECMAScript Modules (ESM) and everyone generally expects npm packages to export things via CommonJS. As such, the source files are built (using Rollup) into a CommonJS package before publishing. To ensure that the published API is working correctly, it makes sense to write the tests in CommonJS and to pull in what would be the published package API.