title: JSON stringify and PostgreSQL bigint compliance
body: <p><a href="https://github.com/vitaly-t/pg-promise/issues/657" rel="noreferrer">I am trying to add <code>BigInt</code> support within my library</a>, and ran into an issue with <code>JSON.stringify</code>.</p>
  
  <p>The nature of the library permits not to worry about type ambiguity and de-serialization, as everything that's serialized goes into the server, and never needs any de-serialization.</p>
  
  <p>I initially came up with the following simplified approach, just to counteract Node.js throwing <code>TypeError: Do not know how to serialize a BigInt</code> at me:</p>
  
  <pre><code>// Does JSON.stringify, with support for BigInt:
  function toJson(data) {
      return JSON.stringify(data, (_, v) =&gt; typeof v === 'bigint' ? v.toString() : v);
  }
  </code></pre>
  
  <p>But since it converts each <code>BigInt</code> into a string, each value ends up wrapped into double quotes.</p>
  
  <p>Is there any work-around, perhaps some trick within Node.js formatting utilities, to produce a result from <code>JSON.stringify</code> where each <code>BigInt</code> would be formatted as an open value? This is what PostgreSQL understands and supports, and so I'm looking for a way to generate JSON with <code>BigInt</code> that's compliant with PostgreSQL.</p>
  
  <p><strong>Example</strong></p>
  
  <pre><code>const obj = {
      value: 123n
  };
  
  console.log(toJson(obj));
  
  // This is what I'm getting: {"value":"123"}
  // This is what I want: {"value":123}
  </code></pre>
  
  <p>Obviously, I cannot just convert <code>BigInt</code> into <code>number</code>, as I would be losing information then. And rewriting the entire <code>JSON.stringify</code> for this probably would be too complicated.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>At this point I have reviewed and played with several polyfills, like these ones:</p>
  
  <ul>
  <li><a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">polyfill-1</a></li>
  <li><a href="https://medium.com/@cookiengineer/why-i-implemented-my-own-json-stringify-and-console-api-c711dac38fa8" rel="noreferrer">polyfill-2</a></li>
  </ul>
  
  <p>But they all seem like an awkward solution, to bring in so much code, and then modify for <code>BigInt</code> support. I am hoping to find something more elegant.</p>