{"_id":"fast-json-stringify@7.2.0","bugs":{"url":"https://github.com/fastify/fast-json-stringify/issues"},"dist":{"shasum":"eca1d6e3d66a80ace8a2af95ec53c6d07f1d4f51","tarball":"http://registry-npm.ywwl.com/fast-json-stringify/download/fast-json-stringify-7.2.0.tgz","fileCount":101,"integrity":"sha512-q18imgm9fEdQVfvJbRJALE9VP/A5HGme0+NUnWcmFYM9rbQbLkZZk20FyIp1LQ8gDOauQKwqMc52YozqFaQyOw==","signatures":[{"sig":"MEUCIA3M+W2cd1buuFFkZhY2P0t4qEex3S1ik5Bx63k7WpHDAiEA3zmnMCk8ahtjzeWzDk1VtgU8n5vuM5054ar0zOlOq8c=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIDgrR0oqXOnQiuzvw3Eu0JH0y6CEQ0H7NjWti0+XU36kAiAewjzZhtEp3UVdYETwi5Jn7/Y5R28ZYq7HVD5xkO2toA=="}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/fast-json-stringify@7.2.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":523251,"size":94630,"noattachment":false,"key":"/fast-json-stringify/-/fast-json-stringify-7.2.0.tgz"},"main":"index.js","name":"fast-json-stringify","type":"commonjs","types":"types/index.d.ts","author":{"name":"Matteo Collina","email":"hello@matteocollina.com"},"funding":[{"url":"https://github.com/sponsors/fastify","type":"github"},{"url":"https://opencollective.com/fastify","type":"opencollective"}],"gitHead":"968bf202868005077f535129262d7ce094d231aa","license":"MIT","scripts":{"lint":"eslint","test":"npm run test:unit && npm run test:typescript","bench":"node --expose-gc ./benchmark/bench.js","lint:fix":"eslint --fix","bench:cmp":"node ./benchmark/bench-cmp-branch.js","benchmark":"node --expose-gc ./benchmark/bench-cmp-lib.js","test:unit":"c8 --100 --all --include=index.js --include=lib/**/*.js --exclude=lib/schema-validator.js node --test","bench:cmp:ci":"node ./benchmark/bench-cmp-branch.js --ci","test:typescript":"tstyche"},"version":"7.2.0","_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"3afe719c-ac3e-45e1-9c28-398d078ff0bf"}},"homepage":"https://github.com/fastify/fast-json-stringify#readme","keywords":["json","stringify","schema","fast"],"repository":{"url":"git+https://github.com/fastify/fast-json-stringify.git","type":"git"},"_npmVersion":"11.19.1","description":"Stringify your JSON at max speed","directories":{},"maintainers":[{"name":"jsumners","email":"james.sumners@gmail.com"},{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"},{"name":"eomm","email":"behemoth89@gmail.com"},{"name":"climba03003","email":"kaka@kakawebsitedemo.com"}],"_nodeVersion":"24.22.1","contributors":[{"url":"https://delvedor.dev","name":"Tomas Della Vedova"},{"name":"Aras Abbasi","email":"aras.abbasi@gmail.com"},{"name":"Manuel Spigolon","email":"behemoth89@gmail.com"},{"url":"https://github.com/fdawgs","name":"Frazer Smith","email":"frazer.dev@icloud.com"}],"dependencies":{"ajv":"^8.12.0","rfdc":"^1.2.0","fast-uri":"^4.0.0","ajv-formats":"^3.0.1","json-schema-ref-resolver":"^3.0.0","@fastify/merge-json-schemas":"^0.2.0"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^12.0.0","eslint":"^9.39.2","tstyche":"^7.1.0","typebox":"^1.0.81","webpack":"^5.104.1","tinybench":"^6.0.0","cli-select":"^1.1.2","simple-git":"^4.0.2","typescript":"~6.0.2","neostandard":"^0.13.0","json-accelerator":"^0.1.7","fast-json-stringify":".","compile-json-stringify":"^0.1.2"},"runkitExampleFilename":"./examples/example.js","_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/fast-json-stringify_7.2.0_1792860121811_0.8557512685037807"},"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__fast-json-stringify__ is significantly faster than `JSON.stringify()` for small payloads.\nIts performance advantage shrinks as your payload grows.\n\n\n### How it works\n\nfast-json-stringify requires a [JSON Schema Draft 7](https://json-schema.org/specification-links#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 `v22.14.0`\n\n```\nFJS creation x 9,696 ops/sec ±0.77% (94 runs sampled)\nCJS creation x 197,267 ops/sec ±0.22% (95 runs sampled)\nAJV Serialize creation x 48,302,927 ops/sec ±2.09% (90 runs sampled)\njson-accelerator creation x 668,430 ops/sec ±0.43% (95 runs sampled)\nJSON.stringify array x 7,924 ops/sec ±0.11% (98 runs sampled)\nfast-json-stringify array default x 7,183 ops/sec ±0.09% (97 runs sampled)\njson-accelerator array x 5,762 ops/sec ±0.27% (99 runs sampled)\nfast-json-stringify array json-stringify x 7,171 ops/sec ±0.17% (97 runs sampled)\ncompile-json-stringify array x 6,889 ops/sec ±0.41% (96 runs sampled)\nAJV Serialize array x 6,945 ops/sec ±0.17% (98 runs sampled)\nJSON.stringify large array x 331 ops/sec ±0.17% (93 runs sampled)\nfast-json-stringify large array default x 208 ops/sec ±0.21% (91 runs sampled)\nfast-json-stringify large array json-stringify x 330 ops/sec ±0.17% (93 runs sampled)\ncompile-json-stringify large array x 318 ops/sec ±0.11% (90 runs sampled)\nAJV Serialize large array x 114 ops/sec ±0.27% (74 runs sampled)\nJSON.stringify long string x 13,452 ops/sec ±0.15% (99 runs sampled)\nfast-json-stringify long string x 13,454 ops/sec ±0.10% (99 runs sampled)\njson-accelerator long string x 13,439 ops/sec ±0.09% (98 runs sampled)\ncompile-json-stringify long string x 13,380 ops/sec ±0.12% (100 runs sampled)\nAJV Serialize long string x 21,932 ops/sec ±0.06% (99 runs sampled)\nJSON.stringify short string x 12,114,052 ops/sec ±0.59% (97 runs sampled)\nfast-json-stringify short string x 29,408,175 ops/sec ±1.12% (91 runs sampled)\njson-accelerator short string x 29,431,694 ops/sec ±1.05% (93 runs sampled)\ncompile-json-stringify short string x 24,740,338 ops/sec ±1.02% (91 runs sampled)\nAJV Serialize short string x 17,841,869 ops/sec ±0.90% (91 runs sampled)\nJSON.stringify obj x 4,577,494 ops/sec ±0.25% (94 runs sampled)\nfast-json-stringify obj x 7,291,157 ops/sec ±0.40% (97 runs sampled)\njson-accelerator obj x 6,473,194 ops/sec ±0.31% (99 runs sampled)\ncompile-json-stringify obj x 14,724,935 ops/sec ±0.50% (96 runs sampled)\nAJV Serialize obj x 8,782,944 ops/sec ±0.45% (93 runs sampled)\nJSON stringify date x 803,522 ops/sec ±0.47% (98 runs sampled)\nfast-json-stringify date format x 1,117,776 ops/sec ±0.69% (95 runs sampled)\njson-accelerate date format x 1,122,419 ops/sec ±0.20% (97 runs sampled)\ncompile-json-stringify date format x 803,214 ops/sec ±0.23% (97 runs sampled)\n```\n\n#### Table of contents:\n- <a href=\"#example\">`Example`</a>\n- <a href=\"#options\">`Options`</a>\n- <a href=\"#api\">`API`</a>\n - <a href=\"#fastJsonStringify\">`fastJsonStringify`</a>\n - <a href=\"#specific\">`Specific use cases`</a>\n - <a href=\"#required\">`Required`</a>\n - <a href=\"#missingFields\">`Missing fields`</a>\n - <a href=\"#patternProperties\">`Pattern Properties`</a>\n - <a href=\"#additionalProperties\">`Additional Properties`</a>\n - <a href=\"#AnyOf-and-OneOf\">`AnyOf` and `OneOf`</a>\n - <a href=\"#ref\">`Reuse - $ref`</a>\n - <a href=\"#long\">`Long integers`</a>\n - <a href=\"#integer\">`Integers`</a>\n - <a href=\"#nullable\">`Nullable`</a>\n - <a href=\"#largearrays\">`Large Arrays`</a>\n- <a href=\"#security\">`Security Notice`</a>\n- <a href=\"#debug\">`Debug Mode`</a>\n- <a href=\"#standalone\">`Standalone Mode`</a>\n- <a href=\"#acknowledgments\">`Acknowledgments`</a>\n- <a href=\"#license\">`License`</a>\n\n\n<a name=\"example\"></a>\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<a name=\"options\"></a>\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  maxDepth: 100\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) Schema strictness defaults to `false`; pass `ajv: { strictSchema: true }` to reject unknown schema keywords or `ajv: { strictSchema: 'log' }` to log warnings. This applies only to schema paths compiled by Ajv, not to every schema processed by fast-json-stringify.\n- `rounding`: setup how the `integer` types will be rounded when not integers. [More details](#integer)\n- `maxDepth`: maximum number of nested schema levels allowed during compilation.\nDefaults to `100` and may be set from `0` to `100`. Schemas that exceed this limit\nare rejected before compilation.\n- `inlineValidators`: when using standalone mode, embed Ajv-generated validator functions in the output instead of compiling schemas at runtime. [More details](#standalone)\n- `largeArrayMechanism`: set the mechanism that should be used to handle large\n(by default `20000` or more items) arrays. [More details](#largearrays)\n- `compileValidators`: when `true`, the `ajv` validators used by `anyOf`, `oneOf` and\n`if/then/else` are compiled during `build()` instead of lazily, on the first serialization\nthat reaches them. This makes `build()` slower but removes a potentially large one-off cost\nfrom the first `stringify()` call. Defaults to `false`.\n\n\n<a name=\"api\"></a>\n## API\n<a name=\"fastJsonStringify\"></a>\n### fastJsonStringify(schema)\n\nBuild a `stringify()` function based on [jsonschema draft 7 spec](https://json-schema.org/specification-links#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<a name=\"specific\"></a>\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/draft/2020-12/draft-bhutton-json-schema-validation-00#rfc.section.7.3.1) 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, the value is not reformatted nor validated: it should already be properly formatted. It is only escaped, so that the resulting document is always valid JSON.\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<a name=\"required\"></a>\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<a name=\"missingFields\"></a>\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<a name=\"defaults\"></a>\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<a name=\"patternProperties\"></a>\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<a name=\"additionalProperties\"></a>\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 <a href=\"#missingFields\">Missing fields</a>.\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        type: 'string'\n      }, {\n        type: '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<a name=\"if-then-else\"></a>\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<a name=\"ref\"></a>\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://datatracker.ietf.org/doc/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<a name=\"long\"></a>\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<a name=\"integer\"></a>\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<a name=\"nullable\"></a>\n#### Nullable\n\nAccording to the [Open API 3.0 specification](https://swagger.io/docs/specification/v3_0/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` -> `0`\n- `number` -> `0`\n- `string` -> `\"\"`\n- `boolean` -> `false`\n- `object` -> `{}`\n- `array` -> `[]`\n\n<a name=\"largearrays\"></a>\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 keeps the full feature set of this lib: every element\nis still coerced to the type declared in `items`, and type errors are still\nthrown. Arrays of plain primitives (`string`, `number`, `integer`) use a\ncopy-then-`JSON.stringify` strategy with their own length cutoffs, see\n[Primitive arrays](#primitive-arrays) below; `largeArraySize` does not affect\nthem.\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<a name=\"primitive-arrays\"></a>\n##### Primitive arrays\n\nWith `largeArrayMechanism: 'default'`, arrays whose `items` schema is a plain\n`{ type: 'string' }`, `{ type: 'number' }` or `{ type: 'integer' }` (no\n`format`, `nullable`, `const`, or combinator keyword; a `$ref` to a plain\nstring schema also qualifies, a `$ref` for `number`/`integer` does not) are\nserialized by copying the elements into a fresh array and calling the native\n`JSON.stringify` on the copy, which is several times faster than appending one\nelement at a time. This happens at or above a length cutoff that does not\ndepend on `largeArraySize`. The cutoffs are the array lengths above which the\ncopy beats the per-element loop, and they depend on the V8 version:\n\n| Node.js | `string` | `number` | `integer` |\n|---|---:|---:|---:|\n| 22 and later | 8 elements | 128 elements | 512 elements |\n| 20 | 128 elements | 300000 elements | 300000 elements |\n\nBelow the cutoff the array is serialized element by element as before. Above\nit, the elements are copied until one is found that is not already of the\ndeclared type (not a string, not a `number`, or not an integer for `integer`);\nthat element and the ones after it go through the regular per-element coercion\nand validation (`null` still becomes `\"\"` or `0`, `rounding` still applies,\n`NaN` still throws). The output is byte-identical either way. Arrays of\n`boolean`, `null`, objects, or any other `items` schema are not affected.\n\nIn [standalone mode](#standalone) the cutoffs are baked into the generated\ncode, so the generated module inherits the cutoffs of the Node.js version that\nran `build()`, not of the one that runs the module.\n\n<a name=\"unsafe\"></a>\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      type: 'string',\n      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<a name=\"security\"></a>\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<a name=\"debug\"></a>\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<a name=\"standalone\"></a>\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', inlineValidators: true })\n\nfs.writeFileSync('stringify.js', code)\nconst stringify = require('stringify.js')\nconsole.log(stringify({ firstName: 'Foo', surname: 'bar' })) // '{\"firstName\":\"Foo\"}'\n```\n\nSet `inlineValidators` to `true` to include the Ajv-generated functions used by\n`anyOf`, `oneOf`, and `if/then/else` in the same output file. This avoids\nrebuilding an Ajv instance and compiling their schemas at runtime. The\ngenerated module still requires `fast-json-stringify` for its serializer and\nmay require Ajv runtime helpers used by the generated validation code. Custom\nAjv formats used by these schemas must support Ajv's standalone code\ngeneration.\n\nThe generated code also bakes in the length cutoffs used for\n[number and integer arrays](#largearrays). Those cutoffs are chosen for the\nNode.js version that ran `build()`; a module built on Node.js 20 and run on\nNode.js 22 or later keeps the Node.js 20 cutoffs, and vice versa. The output is\nthe same either way, only the speed differs.\n\n<a name=\"acknowledgments\"></a>\n## Acknowledgments\n\nThis project was kindly sponsored by [nearForm](https://nearform.com).\n\n<a name=\"license\"></a>\n## License\n\nLicensed under [MIT](./LICENSE).\n","publish_time":1792860121899,"_cnpm_publish_time":1792860121899,"dist-tags":{"latest":"7.3.1","one":"1.21.0"}}