{"id":13447202,"url":"https://github.com/fastify/fast-json-stringify","last_synced_at":"2025-05-13T15:02:54.255Z","repository":{"id":38815313,"uuid":"64334938","full_name":"fastify/fast-json-stringify","owner":"fastify","description":"2x faster than JSON.stringify()","archived":false,"fork":false,"pushed_at":"2025-05-05T06:30:05.000Z","size":944,"stargazers_count":3570,"open_issues_count":34,"forks_count":209,"subscribers_count":31,"default_branch":"main","last_synced_at":"2025-05-05T22:18:04.550Z","etag":null,"topics":["fastify-library","json","speed","stringify"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/fast-json-stringify","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2016-07-27T19:09:25.000Z","updated_at":"2025-05-05T12:05:40.000Z","dependencies_parsed_at":"2023-02-13T20:40:54.833Z","dependency_job_id":"dcd4629e-e469-45eb-a95f-1a770e82941b","html_url":"https://github.com/fastify/fast-json-stringify","commit_stats":{"total_commits":675,"total_committers":108,"mean_commits":6.25,"dds":0.7125925925925927,"last_synced_commit":"665d0b23e80da8bb4f9ed7c7666abd8c73fe426e"},"previous_names":[],"tags_count":159,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffast-json-stringify","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffast-json-stringify/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffast-json-stringify/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffast-json-stringify/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fast-json-stringify/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253092169,"owners_count":21852753,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify-library","json","speed","stringify"],"created_at":"2024-07-31T05:01:10.811Z","updated_at":"2025-05-13T15:02:54.233Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# fast-json-stringify\n\n[![CI](https://github.com/fastify/fast-json-stringify/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fast-json-stringify/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/fast-json-stringify.svg?style=flat)](https://www.npmjs.com/package/fast-json-stringify)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n[![NPM downloads](https://img.shields.io/npm/dm/fast-json-stringify.svg?style=flat)](https://www.npmjs.com/package/fast-json-stringify)\n\n\n__fast-json-stringify__ is significantly faster than `JSON.stringify()` for small payloads.\nIts performance advantage shrinks as your payload grows.\nIt pairs well with [__flatstr__](https://www.npmjs.com/package/flatstr), which triggers a V8 optimization that improves performance when eventually converting the string to a `Buffer`.\n\n\n### How it works\n\nfast-json-stringify requires a [JSON Schema Draft 7](https://json-schema.org/specification-links.html#draft-7) input to generate a fast `stringify` function.\n\n##### Benchmarks\n\n- Machine: `EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD`.\n- Node.js `v18.12.1`\n\n```\nFJS creation x 4,129 ops/sec ±0.82% (92 runs sampled)\nCJS creation x 184,196 ops/sec ±0.12% (97 runs sampled)\nAJV Serialize creation x 61,130,591 ops/sec ±0.40% (92 runs sampled)\nJSON.stringify array x 5,057 ops/sec ±0.10% (100 runs sampled)\nfast-json-stringify array default x 6,243 ops/sec ±0.14% (98 runs sampled)\nfast-json-stringify array json-stringify x 6,261 ops/sec ±0.30% (99 runs sampled)\ncompile-json-stringify array x 6,842 ops/sec ±0.18% (96 runs sampled)\nAJV Serialize array x 6,964 ops/sec ±0.11% (95 runs sampled)\nJSON.stringify large array x 248 ops/sec ±0.07% (90 runs sampled)\nfast-json-stringify large array default x 99.96 ops/sec ±0.22% (74 runs sampled)\nfast-json-stringify large array json-stringify x 248 ops/sec ±0.07% (90 runs sampled)\ncompile-json-stringify large array x 317 ops/sec ±0.09% (89 runs sampled)\nAJV Serialize large array x 111 ops/sec ±0.07% (33 runs sampled)\nJSON.stringify long string x 16,002 ops/sec ±0.09% (98 runs sampled)\nfast-json-stringify long string x 15,979 ops/sec ±0.09% (96 runs sampled)\ncompile-json-stringify long string x 15,952 ops/sec ±0.31% (97 runs sampled)\nAJV Serialize long string x 21,416 ops/sec ±0.08% (98 runs sampled)\nJSON.stringify short string x 12,944,272 ops/sec ±0.09% (96 runs sampled)\nfast-json-stringify short string x 30,585,790 ops/sec ±0.27% (97 runs sampled)\ncompile-json-stringify short string x 30,656,406 ops/sec ±0.12% (96 runs sampled)\nAJV Serialize short string x 30,406,785 ops/sec ±0.37% (96 runs sampled)\nJSON.stringify obj x 3,153,043 ops/sec ±0.33% (99 runs sampled)\nfast-json-stringify obj x 6,866,434 ops/sec ±0.11% (100 runs sampled)\ncompile-json-stringify obj x 15,886,723 ops/sec ±0.15% (98 runs sampled)\nAJV Serialize obj x 8,969,043 ops/sec ±0.36% (97 runs sampled)\nJSON stringify date x 1,126,547 ops/sec ±0.09% (97 runs sampled)\nfast-json-stringify date format x 1,836,188 ops/sec ±0.12% (99 runs sampled)\ncompile-json-stringify date format x 1,125,735 ops/sec ±0.19% (98 runs sampled)\n```\n\n#### Table of contents:\n- \u003ca href=\"#example\"\u003e`Example`\u003c/a\u003e\n- \u003ca href=\"#options\"\u003e`Options`\u003c/a\u003e\n- \u003ca href=\"#api\"\u003e`API`\u003c/a\u003e\n - \u003ca href=\"#fastJsonStringify\"\u003e`fastJsonStringify`\u003c/a\u003e\n - \u003ca href=\"#specific\"\u003e`Specific use cases`\u003c/a\u003e\n - \u003ca href=\"#required\"\u003e`Required`\u003c/a\u003e\n - \u003ca href=\"#missingFields\"\u003e`Missing fields`\u003c/a\u003e\n - \u003ca href=\"#patternProperties\"\u003e`Pattern Properties`\u003c/a\u003e\n - \u003ca href=\"#additionalProperties\"\u003e`Additional Properties`\u003c/a\u003e\n - \u003ca href=\"#AnyOf-and-OneOf\"\u003e`AnyOf` and `OneOf`\u003c/a\u003e\n - \u003ca href=\"#ref\"\u003e`Reuse - $ref`\u003c/a\u003e\n - \u003ca href=\"#long\"\u003e`Long integers`\u003c/a\u003e\n - \u003ca href=\"#integer\"\u003e`Integers`\u003c/a\u003e\n - \u003ca href=\"#nullable\"\u003e`Nullable`\u003c/a\u003e\n - \u003ca href=\"#largearrays\"\u003e`Large Arrays`\u003c/a\u003e\n- \u003ca href=\"#security\"\u003e`Security Notice`\u003c/a\u003e\n- \u003ca href=\"#debug\"\u003e`Debug Mode`\u003c/a\u003e\n- \u003ca href=\"#standalone\"\u003e`Standalone Mode`\u003c/a\u003e\n- \u003ca href=\"#acknowledgments\"\u003e`Acknowledgments`\u003c/a\u003e\n- \u003ca href=\"#license\"\u003e`License`\u003c/a\u003e\n\n\n\u003ca name=\"example\"\u003e\u003c/a\u003e\nTry it out on RunKit: \u003ca href=\"https://runkit.com/npm/fast-json-stringify\"\u003ehttps://runkit.com/npm/fast-json-stringify\u003c/a\u003e\n## Example\n\n```js\nconst fastJson = require('fast-json-stringify')\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    firstName: {\n      type: 'string'\n    },\n    lastName: {\n      type: 'string'\n    },\n    age: {\n      description: 'Age in years',\n      type: 'integer'\n    },\n    reg: {\n      type: 'string'\n    }\n  }\n})\n\nconsole.log(stringify({\n  firstName: 'Matteo',\n  lastName: 'Collina',\n  age: 32,\n  reg: /\"([^\"]|\\\\\")*\"/\n}))\n```\n\n\u003ca name=\"options\"\u003e\u003c/a\u003e\n## Options\n\nOptionally, you may provide to `fast-json-stringify` an option object as the second parameter:\n\n```js\nconst fastJson = require('fast-json-stringify')\nconst stringify = fastJson(mySchema, {\n  schema: { ... },\n  ajv: { ... },\n  rounding: 'ceil'\n})\n```\n\n- `schema`: external schemas references by $ref property. [More details](#ref)\n- `ajv`: [ajv v8 instance's settings](https://ajv.js.org/options.html) for those properties that require `ajv`. [More details](#anyof)\n- `rounding`: setup how the `integer` types will be rounded when not integers. [More details](#integer)\n- `largeArrayMechanism`: set the mechanism that should be used to handle large\n(by default `20000` or more items) arrays. [More details](#largearrays)\n\n\n\u003ca name=\"api\"\u003e\u003c/a\u003e\n## API\n\u003ca name=\"fastJsonStringify\"\u003e\u003c/a\u003e\n### fastJsonStringify(schema)\n\nBuild a `stringify()` function based on [jsonschema draft 7 spec](https://json-schema.org/specification-links.html#draft-7).\n\nSupported types:\n\n * `'string'`\n * `'integer'`\n * `'number'`\n * `'array'`\n * `'object'`\n * `'boolean'`\n * `'null'`\n\nAnd nested ones, too.\n\n\u003ca name=\"specific\"\u003e\u003c/a\u003e\n#### Specific use cases\n\n| Instance | Serialized as                |\n| -------- | ---------------------------- |\n| `Date`   | `string` via `toISOString()` |\n| `RegExp` | `string`                     |\n| `BigInt` | `integer` via `toString`     |\n\n[JSON Schema built-in formats](https://json-schema.org/understanding-json-schema/reference/string.html#built-in-formats) for dates are supported and will be serialized as:\n\n| Format      | Serialized format example  |\n| ----------- | -------------------------- |\n| `date-time` | `2020-04-03T09:11:08.615Z` |\n| `date`      | `2020-04-03`               |\n| `time`      | `09:11:08`                 |\n\n**Note**: In the case of a string formatted Date and not Date Object, there will be no manipulation on it. It should be properly formatted.\n\nExample with a Date object:\n\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema with string date-time field',\n  type: 'string',\n  format: 'date-time'\n})\n\nconst date = new Date()\nconsole.log(stringify(date)) // '\"YYYY-MM-DDTHH:mm:ss.sssZ\"'\n```\n\n\n\u003ca name=\"required\"\u003e\u003c/a\u003e\n#### Required\nYou can set specific fields of an object as required in your schema by adding the field name inside the `required` array in your schema.\nExample:\n```javascript\nconst schema = {\n  title: 'Example Schema with required field',\n  type: 'object',\n  properties: {\n    nickname: {\n      type: 'string'\n    },\n    mail: {\n      type: 'string'\n    }\n  },\n  required: ['mail']\n}\n```\nIf the object to stringify is missing the required field(s), `fast-json-stringify` will throw an error.\n\n\u003ca name=\"missingFields\"\u003e\u003c/a\u003e\n#### Missing fields\nIf a field *is present* in the schema (and is not required) but it *is not present* in the object to stringify, `fast-json-stringify` will not write it in the final string.\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    nickname: {\n      type: 'string'\n    },\n    mail: {\n      type: 'string'\n    }\n  }\n})\n\nconst obj = {\n  mail: 'mail@example.com'\n}\n\nconsole.log(stringify(obj)) // '{\"mail\":\"mail@example.com\"}'\n```\n\n\u003ca name=\"defaults\"\u003e\u003c/a\u003e\n#### Defaults\n`fast-json-stringify` supports `default` jsonschema key in order to serialize a value\nif it is `undefined` or not present.\n\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    nickname: {\n      type: 'string',\n      default: 'the default string'\n    }\n  }\n})\n\nconsole.log(stringify({})) // '{\"nickname\":\"the default string\"}'\nconsole.log(stringify({nickname: 'my-nickname'})) // '{\"nickname\":\"my-nickname\"}'\n```\n\n\u003ca name=\"patternProperties\"\u003e\u003c/a\u003e\n#### Pattern properties\n`fast-json-stringify` supports pattern properties as defined by JSON schema.\n*patternProperties* must be an object, where the key is a valid regex and the value is an object, declared in this way: `{ type: 'type' }`.\n*patternProperties* will work only for the properties that are not explicitly listed in the properties object.\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    nickname: {\n      type: 'string'\n    }\n  },\n  patternProperties: {\n    'num': {\n      type: 'number'\n    },\n    '.*foo$': {\n      type: 'string'\n    }\n  }\n})\n\nconst obj = {\n  nickname: 'nick',\n  matchfoo: 42,\n  otherfoo: 'str',\n  matchnum: 3\n}\n\nconsole.log(stringify(obj)) // '{\"matchfoo\":\"42\",\"otherfoo\":\"str\",\"matchnum\":3,\"nickname\":\"nick\"}'\n```\n\n\u003ca name=\"additionalProperties\"\u003e\u003c/a\u003e\n#### Additional properties\n`fast-json-stringify` supports additional properties as defined by JSON schema.\n*additionalProperties* must be an object or a boolean, declared in this way: `{ type: 'type' }`.\n*additionalProperties* will work only for the properties that are not explicitly listed in the *properties* and *patternProperties* objects.\n\nIf *additionalProperties* is not present or is set to `false`, every property that is not explicitly listed in the *properties* and *patternProperties* objects will be ignored, as described in \u003ca href=\"#missingFields\"\u003eMissing fields\u003c/a\u003e.\nMissing fields are ignored to avoid having to rewrite objects before serializing. However, other schema rules would throw in similar situations.\nIf *additionalProperties* is set to `true`, it will be used by `JSON.stringify` to stringify the additional properties. If you want to achieve maximum performance, we strongly encourage you to use a fixed schema where possible.\nThe additional properties will always be serialized at the end of the object.\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    nickname: {\n      type: 'string'\n    }\n  },\n  patternProperties: {\n    'num': {\n      type: 'number'\n    },\n    '.*foo$': {\n      type: 'string'\n    }\n  },\n  additionalProperties: {\n    type: 'string'\n  }\n})\n\nconst obj = {\n  nickname: 'nick',\n  matchfoo: 42,\n  otherfoo: 'str',\n  matchnum: 3,\n  nomatchstr: 'valar morghulis',\n  nomatchint: 313\n}\n\nconsole.log(stringify(obj)) // '{\"nickname\":\"nick\",\"matchfoo\":\"42\",\"otherfoo\":\"str\",\"matchnum\":3,\"nomatchstr\":\"valar morghulis\",nomatchint:\"313\"}'\n```\n\n#### AnyOf and OneOf\n\n`fast-json-stringify` supports the **anyOf** and **oneOf** keywords as defined by JSON schema. Both must be an array of valid JSON schemas. The different schemas will be tested in the specified order. The more schemas `stringify` has to try before finding a match, the slower it will be.\n\n*anyOf* and *oneOf* use [ajv](https://www.npmjs.com/package/ajv) as a JSON schema validator to find the schema that matches the data. This has an impact on performance—only use it as a last resort.\n\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    'undecidedType': {\n      'anyOf': [{\n\ttype: 'string'\n      }, {\n\ttype: 'boolean'\n      }]\n    }\n  }\n})\n```\n\nWhen specifying object JSON schemas for *anyOf*, add *required* validation keyword to match only the objects with the properties you want.\n\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'array',\n  items: {\n    anyOf: [\n      {\n        type: 'object',\n        properties: {\n          savedId: { type: 'string' }\n        },\n        // without \"required\" validation any object will match\n        required: ['savedId']\n      },\n      {\n        type: 'object',\n        properties: {\n          error: { type: 'string' }\n        },\n        required: ['error']\n      }\n    ]\n  }\n})\n```\n\n\u003ca name=\"if-then-else\"\u003e\u003c/a\u003e\n#### If/then/else\n`fast-json-stringify` supports `if/then/else` jsonschema feature. See [ajv documentation](https://ajv.js.org/keywords.html#ifthenelse).\n\nExample:\n```javascript\nconst stringify = fastJson({\n  'type': 'object',\n  'properties': {\n  },\n  'if': {\n    'properties': {\n      'kind': { 'type': 'string', 'enum': ['foobar'] }\n    }\n  },\n  'then': {\n    'properties': {\n      'kind': { 'type': 'string', 'enum': ['foobar'] },\n      'foo': { 'type': 'string' },\n      'bar': { 'type': 'number' }\n    }\n  },\n  'else': {\n    'properties': {\n      'kind': { 'type': 'string', 'enum': ['greeting'] },\n      'hi': { 'type': 'string' },\n      'hello': { 'type': 'number' }\n    }\n  }\n})\n\nconsole.log(stringify({\n  kind: 'greeting',\n  foo: 'FOO',\n  bar: 42,\n  hi: 'HI',\n  hello: 45\n})) // {\"kind\":\"greeting\",\"hi\":\"HI\",\"hello\":45}\nconsole.log(stringify({\n  kind: 'foobar',\n  foo: 'FOO',\n  bar: 42,\n  hi: 'HI',\n  hello: 45\n})) // {\"kind\":\"foobar\",\"foo\":\"FOO\",\"bar\":42}\n```\n\n**NB** Do not declare the properties twice or you will print them twice!\n\n\u003ca name=\"ref\"\u003e\u003c/a\u003e\n#### Reuse - $ref\nIf you want to reuse a definition of a value, you can use the property `$ref`.\nThe value of `$ref` must be a string in [JSON Pointer](https://tools.ietf.org/html/rfc6901) format.\nExample:\n```javascript\nconst schema = {\n  title: 'Example Schema',\n  definitions: {\n    num: {\n      type: 'object',\n      properties: {\n        int: {\n          type: 'integer'\n        }\n      }\n    },\n    str: {\n      type: 'string'\n    }\n  },\n  type: 'object',\n  properties: {\n    nickname: {\n      $ref: '#/definitions/str'\n    }\n  },\n  patternProperties: {\n    'num': {\n      $ref: '#/definitions/num'\n    }\n  },\n  additionalProperties: {\n    $ref: '#/definitions/def'\n  }\n}\n\nconst stringify = fastJson(schema)\n```\nIf you need to use an external definition, you can pass it as an option to `fast-json-stringify`.\nExample:\n```javascript\nconst schema = {\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    nickname: {\n      $ref: 'strings#/definitions/str'\n    }\n  },\n  patternProperties: {\n    'num': {\n      $ref: 'numbers#/definitions/num'\n    }\n  },\n  additionalProperties: {\n    $ref: 'strings#/definitions/def'\n  }\n}\n\nconst externalSchema = {\n  numbers: {\n    definitions: {\n      num: {\n        type: 'object',\n        properties: {\n          int: {\n            type: 'integer'\n          }\n        }\n      }\n    }\n  },\n  strings: require('./string-def.json')\n}\n\nconst stringify = fastJson(schema, { schema: externalSchema })\n```\nExternal definitions can also reference each other.\nExample:\n```javascript\nconst schema = {\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    foo: {\n      $ref: 'strings#/definitions/foo'\n    }\n  }\n}\n\nconst externalSchema = {\n  strings: {\n    definitions: {\n      foo: {\n        $ref: 'things#/definitions/foo'\n      }\n    }\n  },\n  things: {\n    definitions: {\n      foo: {\n        type: 'string'\n      }\n    }\n  }\n}\n\nconst stringify = fastJson(schema, { schema: externalSchema })\n```\n\n\u003ca name=\"long\"\u003e\u003c/a\u003e\n#### Long integers\nBy default, the library will handle automatically [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt).\n\n\u003ca name=\"integer\"\u003e\u003c/a\u003e\n#### Integers\nThe `type: integer` property will be truncated if a floating point is provided.\nYou can customize this behavior with the `rounding` option that will accept [`round`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round), [`ceil`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil), [`floor`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor), or [`trunc`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc). Default is `trunc`:\n\n```js\nconst stringify = fastJson(schema, { rounding: 'ceil' })\n```\n\n\n\u003ca name=\"nullable\"\u003e\u003c/a\u003e\n#### Nullable\n\nAccording to the [Open API 3.0 specification](https://swagger.io/docs/specification/data-models/data-types/#null), a value that can be null must be declared `nullable`.\n\n##### Nullable object\n```javascript\nconst stringify = fastJson({\n  'title': 'Nullable schema',\n  'type': 'object',\n  'nullable': true,\n  'properties': {\n    'product': {\n      'nullable': true,\n      'type': 'object',\n      'properties': {\n        'name': {\n          'type': 'string'\n        }\n      }\n    }\n  }\n})\n\nconsole.log(stringify({product: {name: \"hello\"}})) // \"{\"product\":{\"name\":\"hello\"}}\"\nconsole.log(stringify({product: null})) // \"{\"product\":null}\"\nconsole.log(stringify(null)) // null\n```\n\nOtherwise, instead of raising an error, null values will be coerced as follows:\n\n- `integer` -\u003e `0`\n- `number` -\u003e `0`\n- `string` -\u003e `\"\"`\n- `boolean` -\u003e `false`\n- `object` -\u003e `{}`\n- `array` -\u003e `[]`\n\n\u003ca name=\"largearrays\"\u003e\u003c/a\u003e\n#### Large Arrays\n\nLarge arrays are, for the scope of this document, defined as arrays containing,\nby default, `20000` elements or more. That value can be adjusted via the option\nparameter `largeArraySize`.\n\nAt some point the overhead caused by the default mechanism used by\n`fast-json-stringify` to handle arrays starts increasing exponentially, leading\nto slow overall executions.\n\n##### Settings\n\nIn order to improve that the user can set the `largeArrayMechanism` and\n`largeArraySize` options.\n\n`largeArrayMechanism`'s default value is `default`. Valid values for it are:\n\n- `default` - This option is a compromise between performance and feature set by\nstill providing the expected functionality out of this lib but giving up some\npossible performance gain. With this option set, **large arrays** would be\nstringified by joining their stringified elements using `Array.join` instead of\nstring concatenation for better performance\n- `json-stringify` - This option will remove support for schema validation\nwithin **large arrays** completely. By doing so the overhead previously\nmentioned is nulled, greatly improving execution time. Mind there's no change\nin behavior for arrays not considered _large_\n\n`largeArraySize`'s default value is `20000`. Valid values for it are\ninteger-like values, such as:\n\n- `20000`\n- `2e4`\n- `'20000'`\n- `'2e4'` - _note this will be converted to `2`, not `20000`_\n- `1.5` - _note this will be converted to `1`_\n\n\u003ca name=\"unsafe\"\u003e\u003c/a\u003e\n#### Unsafe string\nBy default, the library escapes all strings. With the 'unsafe' format, the string isn't escaped. This has a potentially dangerous security issue. You can use it only if you are sure that your data doesn't need escaping. The advantage is a significant performance improvement.\n\nExample:\n```javascript\nconst stringify = fastJson({\n  title: 'Example Schema',\n  type: 'object',\n  properties: {\n    'code': {\n\t    type: 'string',\n\t    format 'unsafe'\n    }\n  }\n})\n```\n\n##### Benchmarks\n\nFor reference, here are some benchmarks for comparison over the three\nmechanisms. Benchmarks were conducted on an old machine.\n\n- Machine: `ST1000LM024 HN-M 1TB HDD, Intel Core i7-3610QM @ 2.3GHz, 12GB RAM, 4C/8T`.\n- Node.js `v16.13.1`\n\n```\nJSON.stringify large array x 157 ops/sec ±0.73% (86 runs sampled)\nfast-json-stringify large array default x 48.72 ops/sec ±4.92% (48 runs sampled)\nfast-json-stringify large array json-stringify x 157 ops/sec ±0.76% (86 runs sampled)\ncompile-json-stringify large array x 175 ops/sec ±4.47% (79 runs sampled)\nAJV Serialize large array x 58.76 ops/sec ±4.59% (60 runs sampled)\n```\n\n\u003ca name=\"security\"\u003e\u003c/a\u003e\n## Security notice\n\nTreat the schema definition as application code, it\nis not safe to use user-provided schemas.\n\nTo achieve low cost and high performance redaction `fast-json-stringify`\ncreates and compiles a function (using the `Function` constructor) on initialization.\nWhile the `schema` is currently validated for any developer errors,\nthere is no guarantee that supplying user-generated schema could not\nexpose your application to remote attacks.\n\nUsers are responsible for sending trusted data. `fast-json-stringify` guarantees that you will get\na valid output only if your input matches the schema or can be coerced to the schema. If your input\ndoesn't match the schema, you will get undefined behavior.\n\n\u003ca name=\"debug\"\u003e\u003c/a\u003e\n### Debug Mode\n\nThe debug mode can be activated during your development to understand what is going on when things do not\nwork as you expect.\n\n```js\nconst debugCompiled = fastJson({\n  title: 'default string',\n  type: 'object',\n  properties: {\n    firstName: {\n      type: 'string'\n    }\n  }\n}, { mode: 'debug' })\n\nconsole.log(debugCompiled) // it is a object contain code, ajv instance\nconst rawString = debugCompiled.code // it is the generated code\nconsole.log(rawString)\n\nconst stringify = fastJson.restore(debugCompiled) // use the generated string to get back the `stringify` function\nconsole.log(stringify({ firstName: 'Foo', surname: 'bar' })) // '{\"firstName\":\"Foo\"}'\n```\n\n\u003ca name=\"standalone\"\u003e\u003c/a\u003e\n### Standalone Mode\n\nThe standalone mode is used to compile the code that can be directly run by `node`\nitself. You need to have `fast-json-stringify` installed for the standalone code to work.\n\n```js\nconst fs = require('fs')\nconst code = fastJson({\n  title: 'default string',\n  type: 'object',\n  properties: {\n    firstName: {\n      type: 'string'\n    }\n  }\n}, { mode: 'standalone' })\n\nfs.writeFileSync('stringify.js', code)\nconst stringify = require('stringify.js')\nconsole.log(stringify({ firstName: 'Foo', surname: 'bar' })) // '{\"firstName\":\"Foo\"}'\n```\n\n\u003ca name=\"acknowledgments\"\u003e\u003c/a\u003e\n## Acknowledgments\n\nThis project was kindly sponsored by [nearForm](https://nearform.com).\n\n\u003ca name=\"license\"\u003e\u003c/a\u003e\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript","Repository","目录","Daily"],"sub_categories":["Object / JSON / JSON Schema"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffast-json-stringify","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffast-json-stringify","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffast-json-stringify/lists"}