# Make \`JSON.stringify\` more fast with JSON Schema

**URL:** <https://es.discourse.group/t/make-json-stringify-more-fast-with-json-schema/1947>\
**Category:** 💡 Ideas\
**Created:** [March 11, 2024, 3:25pm UTC](https://es.discourse.group/t/make-json-stringify-more-fast-with-json-schema/1947 "2024-03-11T15:25:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cesco69](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/cesco69/32/1481_2.png) [@cesco69](https://es.discourse.group/u/cesco69)\
**Post date:** [March 11, 2024, 3:25pm UTC](https://es.discourse.group/t/make-json-stringify-more-fast-with-json-schema/1947/1 "2024-03-11T15:25:52Z")

</div>

`JSON.stringify` is used by web server like [expressjs](https://expressjs.com/) for trasform object into json response. [Fastify](https://fastify.dev/) (an expressjs alternative) is 3x faster because use  
[fast-json-stringify](https://github.com/fastify/fast-json-stringify), `fast-json-stringify` requires a [JSON Schema Draft 7](https://json-schema.org/specification-links.html#draft-7) input to generate a fast `stringify` function. With the JSON schema, `fast-json-stringify` already know the structure of the object and can create a template string with just some placeholder for the value to replace on stringify.

JavaScript could be have a `JSON.Schema` that accept a JSON schema in the same way, ad return an optimized `stringify` function, eg::

```javascript
const stringify = JSON.Schema({
  title: 'Example Schema',
  type: 'object',
  properties: {
    firstName: {
      type: 'string'
    },
    lastName: {
      type: 'string'
    },
    age: {
      description: 'Age in years',
      type: 'integer'
    }
  }
})

console.log(stringify({
  firstName: 'Foo',
  lastName: 'Bar',
  age: 32
}))

```

output

```javascript
{"firstName":"Foo","lastName":"Bar","age":32}

```

Optimized `stringify` method internally has the template of the structure with the placeholder, eg:

```javascript
{"firstName":"$0","lastName":"$1","age":$2}

```

---

<div class="post-metadata">

**Author:** ![aclaymore](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/aclaymore/32/501_2.png) [@aclaymore](https://es.discourse.group/u/aclaymore)\
**Post date:** [March 11, 2024, 6:30pm UTC](https://es.discourse.group/t/make-json-stringify-more-fast-with-json-schema/1947/2 "2024-03-11T18:30:11Z")

</div>

Related thread for parsing instead of serialisation: [Schema-based JSON parsing?](https://es.discourse.group/t/schema-based-json-parsing/1186)
