{"name":"@discoveryjs/json-ext","version":"0.5.6","keywords":["json","utils","stream","async","promise","stringify","info"],"author":{"url":"https://github.com/lahmatiy","name":"Roman Dvornov","email":"rdvornov@gmail.com"},"license":"MIT","_id":"@discoveryjs/json-ext@0.5.6","homepage":"https://github.com/discoveryjs/json-ext#readme","bugs":{"url":"https://github.com/discoveryjs/json-ext/issues"},"dist":{"shasum":"d5e0706cf8c6acd8c6032f8d54070af261bbbb2f","tarball":"http://registry-npm.ywwl.com/@discoveryjs/json-ext/download/@discoveryjs/json-ext-0.5.6.tgz","fileCount":14,"integrity":"sha512-ws57AidsDvREKrZKYffXddNkyaF14iHNHm8VQnZH6t99E8gczjNN0GpvcGny0imC80yQ0tHz1xVUKk/KFQSUyA==","signatures":[{"sig":"MEUCIQD2XuT09XthvJPHi9nJJbYKTyXf5Q6yYH8MtSnMEpLfdwIgMxCkZB7QQwCfDgbHJ/neClOkZcqz1SxHKr5xemopOGM=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":83294,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJhpp+8CRA9TVsSAnZWagAAtuIP/3tnkcjXUk3JlQamZa8H\n9wmm3UWBCyBydbMZNAZqv6rfTmXF/DIqz1b3Hs1Ll0Laf8X+NmBqAeZmlmzs\n5udSilWBUkSl9t7XaDeaFRdpSyKj1cl4vbkWcOqawqJ8J4t9x8/VxgAEUwH7\nBbMY7pkzRfHmY4c3A0I+pjwvhOgN1LK4I7yebx6G2PuWMm0i/e+C2k5jFmCq\nQrgtS955h0cwdEpG17EIC0QsXbfn1mPPozUKmOqmniXQFRY+UfoXtBBY3GeQ\nScorPtDkjM+TCwFPa+37fUIT3Ml5NVHUgu2OtOMqBpOO17oLd9r05jlu5hhI\nQhgnwcjZ4P3Bi5i6WPXqm6KdTJ1HdADw57+SpN301nnBu2+hFPROwguFNkQi\nag0UGOYpVioVZotLH4NdTYXxmrUzUKuo8t0aA5N4dhmG8b1v45zhDr1qYHXU\nymrmn4o0CFTrQOHxzuspJDnrvVwgQ+J3tFnAFHrClNYARCzyGnWdopqCxNPY\nJkj4EDo6B9kYFOnq5atb6UwV/NqLgSzZDr/rR3QjSVChYenQbTC245bsksqL\nrAGIqmaT2c72WtavCbz3QNetaxpgGsZKpEuNjrUpgeRzeQsMvg6CY4fy1PMw\n+30IjhyOSxjmPyZjndlYVGrWEBzTzNpNdaZWEcMmclERYFuljDYLpbsQR3Mq\nqFmk\r\n=lnm8\r\n-----END PGP SIGNATURE-----\r\n","size":19019,"noattachment":false,"key":"/@discoveryjs/json-ext/-/@discoveryjs/json-ext-0.5.6.tgz"},"main":"./src/index","types":"./index.d.ts","browser":{"./src/text-decoder.js":"./src/text-decoder-browser.js","./src/stringify-stream.js":"./src/stringify-stream-browser.js"},"engines":{"node":">=10.0.0"},"gitHead":"baf1f9567e098d7d03fc0f07b335560e53aa166a","scripts":{"lint":"eslint src test","test":"mocha --reporter progress","build":"rollup --config","travis":"nyc npm run lint-and-test && npm run build-and-test && npm run coveralls","coverage":"nyc npm test","test:all":"npm run test:src && npm run test:dist","test:src":"npm test","coveralls":"nyc report --reporter=text-lcov | coveralls","test:dist":"cross-env MODE=dist npm test && cross-env MODE=dist-min npm test","lint-and-test":"npm run lint && npm test","build-and-test":"npm run build && npm run test:dist","prepublishOnly":"npm run build"},"_npmUser":{"name":"lahmatiy","email":"rdvornov@gmail.com"},"repository":{"url":"git+https://github.com/discoveryjs/json-ext.git","type":"git"},"_npmVersion":"8.1.0","description":"A set of utilities that extend the use of JSON","directories":{},"_nodeVersion":"16.13.0","dependencies":{},"_hasShrinkwrap":false,"devDependencies":{"nyc":"^15.1.0","chalk":"^4.1.0","mocha":"^8.1.1","eslint":"^7.6.0","rollup":"^2.28.2","coveralls":"^3.1.0","cross-env":"^7.0.3","@rollup/plugin-json":"^4.1.0","rollup-plugin-terser":"^7.0.2","@rollup/plugin-commonjs":"^15.1.0","@rollup/plugin-node-resolve":"^9.0.0"},"_npmOperationalInternal":{"tmp":"tmp/json-ext_0.5.6_1638309820062_0.5492637512489906","host":"s3://npm-registry-packages"},"readme":"# json-ext\n\n[![NPM version](https://img.shields.io/npm/v/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext)\n[![Build Status](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml/badge.svg)](https://github.com/discoveryjs/json-ext/actions/workflows/ci.yml)\n[![Coverage Status](https://coveralls.io/repos/github/discoveryjs/json-ext/badge.svg?branch=master)](https://coveralls.io/github/discoveryjs/json-ext)\n[![NPM Downloads](https://img.shields.io/npm/dm/@discoveryjs/json-ext.svg)](https://www.npmjs.com/package/@discoveryjs/json-ext)\n\nA set of utilities that extend the use of JSON:\n\n- [parseChunked()](#parsechunked) – functions like [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) but iterates over chunks, reconstructing the result object.\n- [stringifyChunked()](#stringifychunked) – functions like [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), but returns a generator yielding strings instead of a single string.\n- [stringifyInfo()](#stringifyinfo) – returns an object with the expected overall size of the stringify operation and any circular references.\n- [parseFromWebStream()](#parsefromwebstream) – a helper function to consume chunks from a Web Stream.\n- [createStringifyWebStream()](#createstringifywebstream) – a helper to create a Web Stream.\n\nFeatures:\n\n- Fast and memory-efficient\n- Compatible with browsers, Node.js, Deno, Bun\n- Supports Node.js and Web streams\n- Dual package: ESM and CommonJS\n- No dependencies\n- Size: 9.4Kb (minified), 3.6Kb (min+gzip)\n\n## Why?\n\n- Prevents main thread freezing during large JSON parsing by distributing the process over time.\n- Handles large JSON processing (e.g., V8 has a limitation for strings ~500MB, making JSON larger than 500MB unmanageable).\n- Reduces memory pressure. `JSON.parse()` and `JSON.stringify()` require the entire JSON content before processing. `parseChunked()` and `stringifyChunked()` allow processing and sending data incrementally, avoiding large memory consumption at a single time point and reducing GC pressure.\n\n## Install\n\n```bash\nnpm install @discoveryjs/json-ext\n```\n\n## API\n\n### parseChunked()\n\nFunctions like [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse), iterating over chunks to reconstruct the result object, and returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n\n> Note: `reviver` parameter is not supported yet.\n\n```ts\nfunction parseChunked(input: Iterable<Chunk> | AsyncIterable<Chunk>): Promise<any>;\nfunction parseChunked(input: () => (Iterable<Chunk> | AsyncIterable<Chunk>)): Promise<any>;\n\ntype Chunk = string | Buffer | Uint8Array;\n```\n\n[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#parse-chunked)\n\nUsage:\n\n```js\nimport { parseChunked } from '@discoveryjs/json-ext';\n\nconst data = await parseChunked(chunkEmitter);\n```\n\nParameter `chunkEmitter` can be an iterable or async iterable that iterates over chunks, or a function returning such a value. A chunk can be a `string`, `Uint8Array`, or Node.js `Buffer`.\n\nExamples:\n\n- Generator:\n    ```js\n    parseChunked(function*() {\n        yield '{ \"hello\":';\n        yield Buffer.from(' \"wor'); // Node.js only\n        yield new TextEncoder().encode('ld\" }'); // returns Uint8Array\n    });\n    ```\n- Async generator:\n    ```js\n    parseChunked(async function*() {\n        for await (const chunk of someAsyncSource) {\n            yield chunk;\n        }\n    });\n    ```\n- Array:\n    ```js\n    parseChunked(['{ \"hello\":', ' \"world\"}'])\n    ```\n- Function returning iterable:\n    ```js\n    parseChunked(() => ['{ \"hello\":', ' \"world\"}'])\n    ```\n- Node.js [`Readable`](https://nodejs.org/dist/latest-v14.x/docs/api/stream.html#stream_readable_streams) stream:\n    ```js\n    import { parseChunked } from '@discoveryjs/json-ext';\n    import fs from 'node:fs';\n\n    parseChunked(fs.createReadStream('path/to/file.json'))\n    ```\n- Web stream (e.g., using [fetch()](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)):\n    > Note: Iterability for Web streams was added later in the Web platform, not all environments support it. Consider using `parseFromWebStream()` for broader compatibility.\n    ```js\n    const response = await fetch('https://example.com/data.json');\n    const data = await parseChunked(response.body); // body is ReadableStream\n    ```\n\n### stringifyChunked()\n\nFunctions like [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), but returns a generator yielding strings instead of a single string.\n\n> Note: Returns `\"null\"` when `JSON.stringify()` returns `undefined` (since a chunk cannot be `undefined`).\n\n```ts\nfunction stringifyChunked(value: any, replacer?: Replacer, space?: Space): Generator<string, void, unknown>;\nfunction stringifyChunked(value: any, options: StringifyOptions): Generator<string, void, unknown>;\n\ntype Replacer =\n    | ((this: any, key: string, value: any) => any)\n    | (string | number)[]\n    | null;\ntype Space = string | number | null;\ntype StringifyOptions = {\n    replacer?: Replacer;\n    space?: Space;\n    highWaterMark?: number;\n};\n```\n\n[Benchmark](https://github.com/discoveryjs/json-ext/tree/master/benchmarks#stream-stringifying)\n\nUsage:\n\n```js\nimport { stringifyStream } from '@discoveryjs/json-ext';\n\nconst chunks = [...stringifyChunked(data)];\n// or\nfor (const chunk of stringifyChunked(data)) {\n    console.log(chunk);\n}\n```\n\nExamples:\n\n- Streaming into a file (Node.js):\n    ```js\n    Readable.from(stringifyChunked(data))\n        .pipe(fs.createWriteStream('path/to/file.json'));\n    ```\n- Wrapping into a `Promise` for piping into a writable Node.js stream:\n    ```js\n    new Promise((resolve, reject) => {\n        Readable.from(stringifyChunked(data))\n            .on('error', reject)\n            .pipe(stream)\n            .on('error', reject)\n            .on('finish', resolve);\n    });\n    ```\n- Using with fetch (JSON streaming):\n    > Note: This feature has limited support in browsers, see [Streaming requests with the fetch API](https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests)\n\n    > Note: `ReadableStream.from()` has limited [support in browsers](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/from_static), use [`createStringifyWebStream()`](#createstringifywebstream) instead.\n    ```js\n    fetch('http://example.com', {\n        method: 'POST',\n        duplex: 'half',\n        body: ReadableStream.from(stringifyChunked(data))\n    });\n    ```\n- Wrapping into `ReadableStream`:\n    > Note: Use `ReadableStream.from()` or [`createStringifyWebStream()`](#createstringifywebstream) when no extra logic is needed\n    ```js\n    new ReadableStream({\n        start() {\n            this.generator = stringifyChunked(data);\n        },\n        pull(controller) {\n            const { value, done } = this.generator.next();\n\n            if (done) {\n                controller.close();\n            } else {\n                controller.enqueue(value);\n            }\n        },\n        cancel() {\n            this.generator = null;\n        }\n    });\n    ```\n\n### stringifyInfo()\n\n```ts\nexport function stringifyInfo(value: any, replacer?: Replacer, space?: Space): StringifyInfoResult;\nexport function stringifyInfo(value: any, options?: StringifyInfoOptions): StringifyInfoResult;\n\ntype StringifyInfoOptions = {\n    replacer?: Replacer;\n    space?: Space;\n    continueOnCircular?: boolean;\n}\ntype StringifyInfoResult = {\n    minLength: number;\n    circular: Object[]; // list of circular references\n};\n```\n\nFunctions like [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify), but returns an object with the expected overall size of the stringify operation and a list of circular references.\n\nExample:\n\n```js\nimport { stringifyInfo } from '@discoveryjs/json-ext';\n\nconsole.log(stringifyInfo({ test: true }));\n// {\n//   bytes: 13, // Buffer.byteLength('{\"test\":true}')\n//   circular: []    \n// }\n```\n\n#### Options\n\n##### continueOnCircular\n\nType: `Boolean`  \nDefault: `false`\n\nDetermines whether to continue collecting info for a value when a circular reference is found. Setting this option to `true` allows finding all circular references.\n\n### parseFromWebStream()\n\nA helper function to consume JSON from a Web Stream. You can use `parseChunked(stream)` instead, but `@@asyncIterator` on `ReadableStream` has limited support in browsers (see [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) compatibility table).\n\n```js\nimport { parseFromWebStream } from '@discoveryjs/json-ext';\n\nconst data = await parseFromWebStream(readableStream);\n// equivalent to (when ReadableStream[@@asyncIterator] is supported):\n// await parseChunked(readableStream);\n```\n\n### createStringifyWebStream()\n\nA helper function to convert `stringifyChunked()` into a `ReadableStream` (Web Stream). You can use `ReadableStream.from()` instead, but this method has limited support in browsers (see [ReadableStream.from()](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/from_static) compatibility table).\n\n```js\nimport { createStringifyWebStream } from '@discoveryjs/json-ext';\n\ncreateStringifyWebStream({ test: true });\n// equivalent to (when ReadableStream.from() is supported):\n// ReadableStream.from(stringifyChunked({ test: true }))\n```\n\n## License\n\nMIT\n","publish_time":1638309820220,"maintainers":[{"name":"lahmatiy","email":"rdvornov@gmail.com"},{"name":"smelukov","email":"s.melukov@gmail.com"},{"name":"exdis","email":"exsdis@gmail.com"}],"_cnpm_publish_time":1638309820220,"dist-tags":{"latest":"1.1.0"}}