{"name":"@streamparser/json","description":"Streaming JSON parser in Javascript for Node.js, Deno and the browser","version":"0.0.5","main":"./dist/cjs/index.js","module":"./dist/mjs/index.js","browser":"./dist/umd/index.js","types":"./dist/index.d.ts","author":{"name":"Juanjo Diaz","email":"juanjo.diazmo@gmail.com"},"repository":{"type":"git","url":"git+https://github.com/juanjoDiaz/streamparser-json.git"},"bugs":{"url":"https://github.com/juanjoDiaz/streamparser-json/issues"},"devDependencies":{"@types/node":"^14.14.6","rollup":"^2.33.1","rollup-plugin-typescript2":"^0.27.3","tap":"^14.10.8","typescript":"^4.0.5"},"scripts":{"build:deno":"node build.deno.js ./src ./dist/deno","build:umd":"rollup -c","build:cjs":"tsc --module commonjs --outDir ./dist/cjs","build:mjs":"tsc --module esnext --outDir ./dist/mjs && node build.mjs.js ./dist/mjs","build":"npm run build:umd && npm run build:cjs && npm run build:mjs && npm run build:deno","prepare":"npm run build","test":"TS_NODE_SKIP_PROJECT=true tap --timeout=60 test"},"license":"MIT","tags":["json","stream"],"dependencies":{},"gitHead":"3525656155b4ced5159bc3ab37ea07a1f8132677","homepage":"https://github.com/juanjoDiaz/streamparser-json#readme","_id":"@streamparser/json@0.0.5","_nodeVersion":"14.15.0","_npmVersion":"6.14.8","dist":{"integrity":"sha512-6n95rO27+4qrpkM0zUzhCuG1LE1+NlYs3MHlleDOeUo+D+Ov4YTGeal5k1ANGeIpTYbScQCtJtpKQFJH+OVd0Q==","shasum":"65eecd0078a924828f905028ed641d64478842cd","tarball":"http://registry-npm.ywwl.com/@streamparser/json/download/@streamparser/json-0.0.5.tgz","fileCount":72,"unpackedSize":243006,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfrwRfCRA9TVsSAnZWagAA/s8QAJBvE4rnLRxko7hc9dPp\n5F6HdMQkVJm5D3ueNGTUd7R2v9dAYq6MHt2A55FM7Djz9vD6Fej3m1PgxULH\nnJIiwJCgyhBc20iyxbo6l1N9sh/A4OTQR4UsNXJ9eNWYQKZ7yCBLa6cehWH4\nr/utuL11Oj4cuFsNomD4FC69YvZBArzFhY3P0MN+j4k0VD0yFXYblmuxTJKL\nSW1fTp9GqB16a6c/+z8KqfRbWE0G29VQ1K6Jpfanc6F5fGf49I0uDf9auTmL\nnjkVYFRJRfxtcwOw1sQO3jZUzJsFljRbY8/mp018Xp3wOkcHi3R26CXwqJgA\nHtiy+2FIQOOXrDkXqp6is/3kiLhX0xjubzpo3w9+9vzqer2cflanbiqLYNav\n49TFk7fTe6Of3WJve57rx8462n2m8gKaog7QYNG+4foxJMbYR4C7zIfN+KK7\nz1N8BlunHghev8nbY0IusnZYKPpQxdl+ZOzWA5L118gvMOkC+CTYuifo1ONc\n2/YIrWqh/OAa9RBotPytJMosEyuAt5czUe3j0sB8ebnp9/jhfJ4DO6PWcSmd\naSVlIvZ9l2cqDrNgnPmAeLBJ71cdCClO2sZs+nCvmfsM/yPc8PLJumjTABuN\ngnCbz+3rNMrHRzHzzqK1BQOPq/CzWyqvJmJ0fSMiGs0d6jlTxsoe1N14Ajez\n4nTX\r\n=2Tks\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDbAeeyOwiwA10+IbwW4LSrPWMmda7WS+AObJH0Mo18IAiEAz+kzE53XS0r4mYMbm6OXE5t3s9b4smNpC5RCW9k8tQs="}],"size":36713,"noattachment":false,"key":"/@streamparser/json/-/@streamparser/json-0.0.5.tgz"},"_npmUser":{"name":"juanjodiaz","email":"juanjo.diazmo@gmail.com"},"directories":{},"maintainers":[{"name":"juanjodiaz","email":"juanjo.diazmo@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/json_0.0.5_1605305438989_0.6276664683887907"},"_hasShrinkwrap":false,"readme":"# @streamparser/json\n\n[![npm version][npm-version-badge]][npm-badge-url]\n[![npm monthly downloads][npm-downloads-badge]][npm-badge-url]\n[![Build Status][build-status-badge]][build-status-url]\n[![Coverage Status][coverage-status-badge]][coverage-status-url]\n\nFast dependency-free library to parse a JSON stream using utf-8 encoding in Node.js, Deno or any modern browser. Fully compliant with the JSON spec and `JSON.parse(...)`.\n\n*tldr;*\n\n```javascript\nimport { JSONParser } from '@streamparser/json';\n\nconst parser = new JSONParser();\nparser.onValue = ({ value }) => { /* process data */ };\n\n// Or passing the stream in several chunks \ntry {\n  parser.write('{ \"test\": [\"a\"] }');\n  // onValue will be called 3 times:\n  // \"a\"\n  // [\"a\"]\n  // { test: [\"a\"] }\n} catch (err) {\n  console.log(err); // handler errors \n}\n```\n\n## @streamparser/json ecosystem\n\nThere are multiple flavours of @streamparser:\n\n* The **[@streamparser/json](https://www.npmjs.com/package/@streamparser/json)** package allows to parse any JSON string or stream using pure Javascript.\n* The **[@streamparser/json-whatwg](https://www.npmjs.com/package/@streamparser/json-whatwg)** wraps `@streamparser/json` into a WHATWG TransformStream.\n* The **[@streamparser/json-node](https://www.npmjs.com/package/@streamparser/json-node)** wraps `@streamparser/json` into a node Transform stream.\n\n## Dependencies / Polyfilling\n\n@streamparser/json requires a few ES6 classes:\n\n* [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\n* [TextEncoder](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder)\n* [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder)\n\nIf you are targeting browsers or systems in which these might be missing, you need to polyfil them.\n\n## Components\n\n### Tokenizer\n\nA JSON compliant tokenizer that parses a utf-8 stream into JSON tokens\n\n```javascript\nimport { Tokenizer } from '@streamparser/json';\n\nconst tokenizer = new Tokenizer(opts);\n```\n\nThe available options are:\n\n```javascript\n{\n  stringBufferSize: <number>, // set to 0 to don't buffer. Min valid value is 4.\n  numberBufferSize: <number>, // set to 0 to don't buffer.\n  separator: <string>, // separator between object. For example `\\n` for nd-js.\n  emitPartialTokens: <boolean> // whether to emit tokens mid-parsing.\n}\n```\n\nIf buffer sizes are set to anything else than zero, instead of using a string to apppend the data as it comes in, the data is buffered using a TypedArray. A reasonable size could be `64 * 1024` (64 KB).\n\n#### Buffering\n\nWhen parsing strings or numbers, the parser needs to gather the data in-memory until the whole value is ready.\n\nStrings are inmutable in Javascript so every string operation creates a new string. The V8 engine, behind Node, Deno and most modern browsers, performs a many different types of optimization. One of this optimizations is to over-allocate memory when it detects many string concatenations. This increases significatly the memory consumption and can easily exhaust your memory when parsing JSON containing very large strings or numbers. For those cases, the parser can buffer the characters using a TypedArray. This requires encoding/decoding from/to the buffer into an actual string once the value is ready. This is done using the `TextEncoder` and `TextDecoder` APIs. Unfortunately, these APIs creates a significant overhead when the strings are small so should be used only when strictly necessary.\n\n#### Properties & Methods\n\n* **write(data: string|typedArray|buffer)** push data into the tokenizer.\n* **end()** closes the tokenizer so it can not be used anymore. Throws an error if the tokenizer was in the middle of parsing.\n* **isEnded** readonly boolean property indicating whether the Tokenizer is ended or is still accepting data.\n* **parseNumber(numberStr)** method used internally to parse numbers. By default, it is equivalent to `Number(numberStr)` but the user can override it if he wants some other behaviour.\n* **onToken({ token: TokenType, value: any, offset: number })** no-op method that the user should override to follow the tokenization process.\n* **onError(err: Error)** no-op method that the user can override to act on errors. If not set, the write method simply throws synchronously.\n* **onEnd()** no-op method that the user can override to act when the tokenizer is ended.\n \n```javascript\n// You can override the overridable methods by creating your own class extending Tokenizer\nclass MyTokenizer extends Tokenizer {\n  parseNumber(numberStr) {\n    const number = super.parseNumber(numberStr);\n    // if number is too large. Just keep the string.\n    return Number.isFinite(numberStr) ? number : numberStr;\n  }\n  onToken({ token, value }) {\n    if (token = TokenTypes.NUMBER && typeof value === 'string') {\n      super(TokenTypes.STRING, value);\n    } else {\n      super(token, value);\n    }\n  }\n}\n\nconst myTokenizer = new MyTokenizer();\n\n// or just overriding it\nconst tokenizer = new Tokenizer();\ntokenizer.parseNumber = (numberStr) => { ... };\ntokenizer.onToken = ({ token, value, offset }) => { ... };\n```\n\n### TokenParser\n\nA token parser that processes JSON tokens as emitted by the `Tokenizer` and emits JSON values/objects.\n\n```javascript\nimport { TokenParser} from '@streamparser/json';\n\nconst tokenParser = new TokenParser(opts);\n```\n\nThe available options are:\n\n```javascript\n{\n  paths: <string[]>,\n  keepStack: <boolean>, // whether to keep all the properties in the stack\n  separator: <string>, // separator between object. For example `\\n` for nd-js. If left empty or set to undefined, the token parser will end after parsing the first object. To parse multiple object without any delimiter just set it to the empty string `''`.\n  emitPartialValues: <boolean>, // whether to emit values mid-parsing.\n}\n```\n\n* paths: Array of paths to emit. Defaults to `undefined` which emits everything. The paths are intended to suppot jsonpath although at the time being it only supports the root object selector (`$`) and subproperties selectors including wildcards (`$.a`, `$.*`, `$.a.b`, , `$.*.b`, etc). \n* keepStack: Whether to keep full objects on the stack even if they won't be emitted. Defaults to `true`. When set to `false` the it does preserve properties in the parent object some ancestor will be emitted. This means that the parent object passed to the `onValue` function will be empty, which doesn't reflect the truth, but it's more memory-efficient.\n\n#### Properties & Methods\n\n* **write(token: TokenType, value: any)** push data into the token parser.\n* **end()** closes the token parser so it can not be used anymore. Throws an error if the tokenizer was in the middle of parsing.\n* **isEnded** readonly boolean property indicating whether the token parser is ended or is still accepting data.\n* **onValue(value: any)** no-op method that the user should override to get the parsed value.\n* **onError(err: Error)** no-op method that the user should override to act on errors. If not set, the write method simply throws synchronously.\n* **onEnd()** no-op method that the user should override to act when the token parser is ended.\n \n```javascript\n// You can override the overridable methods by creating your own class extending Tokenizer\nclass MyTokenParser extends TokenParser {\n  onValue(value: any) {\n    // ...\n  }\n}\n\nconst myTokenParser = new MyTokenParser();\n\n// or just overriding it\nconst tokenParser = new TokenParser();\ntokenParser.onValue = (value) => { ... };\n```\n\n### JSONParser\n\nA drop-in replacement of `JSONparse` (with few ~~breaking changes~~ improvements. See below.).\n\n\n```javascript\nimport { JSONParser } from '@streamparser/json';\n\nconst parser = new JSONParser();\n```\n\nIt takes the same options as the tokenizer.\n\nThis class is just for convenience. In reality, it simply connects the tokenizer and the parser:\n\n```javascript\nconst tokenizer = new Tokenizer(opts);\nconst tokenParser = new TokenParser();\ntokenizer.onToken = tokenParser.write.bind(tokenParser);\ntokenParser.onValue = (value) => { /* Process values */ }\n```\n\n#### Properties & Methods\n\n* **write(token: TokenType, value: any)** alias to the Tokenizer write method.\n* **end()** alias to the Tokenizer end method.\n* **isEnded** readonly boolean property indicating whether the JSONParser is ended or is still accepting data.\n* **onToken(token: TokenType, value: any, offset: number)** alias to the Tokenizer onToken method. (write only).\n* **onValue(value: any)** alias to the Token Parser onValue method (write only).\n* **onError(err: Error)** alias to the Tokenizer/Token Parser onError method  (write only).\n* **onEnd()** alias to the Tokenizer onEnd method (which will call the Token Parser onEnd methods) (write only).\n \n```javascript\n// You can override the overridable methods by creating your own class extending Tokenizer\nclass MyJsonParser extends JSONParser {\n  onToken(value: any) {\n    // ...\n  }\n  onValue(value: any) {\n    // ...\n  }\n}\n\nconst myJsonParser = new MyJsonParser();\n\n// or just overriding it\nconst jsonParser = new JSONParser();\njsonParser.onToken = (token, value, offset) => { ... };\njsonParser.onValue = (value) => { ... };\n```\n\n## Usage\n\nYou can use both components independently as\n\n```javascript\nconst tokenizer = new Tokenizer(opts);\nconst tokenParser = new TokenParser();\ntokenizer.onToken = tokenParser.write.bind(tokenParser);\n```\n\nYou push data using the `write` method which takes a string or an array-like object.\n\nYou can subscribe to the resulting data using the \n\n```javascript\nimport { JSONParser } from '@streamparser/json';\n\nconst parser = new JSONParser({ stringBufferSize: undefined, paths: ['$'] });\nparser.onValue = console.log;\n\nparser.write('\"Hello world!\"'); // logs \"Hello world!\"\n\n// Or passing the stream in several chunks \nparser.write('\"');\nparser.write('Hello');\nparser.write(' ');\nparser.write('world!');\nparser.write('\"');// logs \"Hello world!\"\n```\n\nWrite is always a synchronous operation so any error during the parsing of the stream will be thrown during the write operation. After an error, the parser can't continue parsing.\n\n```javascript\nimport { JSONParser } from '@streamparser/json';\n\nconst parser = new JSONParser({ stringBufferSize: undefined });\nparser.onValue = console.log;\n\ntry {\n  parser.write('\"\"\"');\n} catch (err) {\n  console.log(err); // logs \n}\n```\n\nYou can also handle errors using callbacks:\n\n```javascript\nimport { JSONParser } from '@streamparser/json';\n\nconst parser = new JSONParser({ stringBufferSize: undefined });\nparser.onValue = console.log;\nparser.onError = console.error;\n\nparser.write('\"\"\"');\n```\n\n## Examples\n\n### Stream-parsing a fetch request returning a JSONstream\n\nImagine an endpoint that send a large amount of JSON objects one after the other (`{\"id\":1}{\"id\":2}{\"id\":3}...`).\n\n```js\n  import { JSONParser} from '@streamparser/json';\n\n  const parser = new JSONParser();\n  parser.onValue = (value, key, parent, stack) => {\n    if (stack > 0) return; // ignore inner values\n    // TODO process element\n  };\n\n  const response = await fetch('http://example.com/');\n  const reader = response.body.getReader();\n  while(true) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    jsonparser.write(value);\n  }\n```\n\n### Stream-parsing a fetch request returning a JSON array\n\nImagine an endpoint that send a large amount of JSON objects one after the other (`[{\"id\":1},{\"id\":2},{\"id\":3},...]`).\n\n```js\n  import { JSONParser } from '@streamparser/json';\n\n  const jsonparser = new JSONParser({ stringBufferSize: undefined, paths: ['$.*'] });\n  jsonparser.onValue = ({ value, key, parent, stack }) => {\n    // TODO process element\n  };\n\n  const response = await fetch('http://example.com/');\n  const reader = response.body.getReader();\n  while(true) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    jsonparser.write(value);\n  }\n```\n\n### Stream-parsing a fetch request returning a very long string getting previews of the string\n\nImagine an endpoint that send a large amount of JSON objects one after the other (`\"Once upon a midnight <...>\"`).\n\n```js\n  import { JSONParser } from '@streamparser/json';\n\n  const jsonparser = new JSONParser({ emitPartialTokens: true, emitPartialValues: true });\n  jsonparser.onValue = ({ value, key, parent, stack, partial }) => {\n    if (partial) {\n      console.log(`Parsing value: ${value}... (still parsing)`);\n    } else {\n      console.log(`Value parsed: ${value}`);\n    }\n  };\n\n  const response = await fetch('http://example.com/');\n  const reader = response.body.getReader();\n  while(true) {\n    const { done, value } = await reader.read();\n    if (done) break;\n    jsonparser.write(value);\n  }\n```\n\n## Migration guide\n\n### Upgrading from 0.10 to 0.11\n\nThe arguments of callbacks have been objectified.\n\nWhat used to be\n\n```js\njsonparser.onToken = ({ token, value }) => {\n  // TODO process token\n};\njsonparser.onValue = ({ value, key, parent, stack }) => {\n  // TODO process element\n};\n```\nnow is:\n\n```js\njsonparser.onToken = (token, value) => {\n  // TODO process token\n};\njsonparser.onValue = (value, key, parent, stack) => {\n  // TODO process element\n};\n```\n\n## License\n\nSee [LICENSE.md](../../LICENSE).\n\n[npm-version-badge]: https://badge.fury.io/js/@streamparser%2Fjson.svg\n[npm-badge-url]: https://www.npmjs.com/package/@streamparser/json\n[npm-downloads-badge]: https://img.shields.io/npm/dm/@streamparser%2Fjson.svg\n[build-status-badge]: https://github.com/juanjoDiaz/streamparser-json/actions/workflows/on-push.yaml/badge.svg\n[build-status-url]: https://github.com/juanjoDiaz/streamparser-json/actions/workflows/on-push.yaml\n[coverage-status-badge]: https://coveralls.io/repos/github/juanjoDiaz/streamparser-json/badge.svg?branch=main\n[coverage-status-url]: https://coveralls.io/github/juanjoDiaz/streamparser-json?branch=main\n","publish_time":1605305439155,"_cnpm_publish_time":1605305439155,"dist-tags":{"latest":"0.0.26"}}