jsonc Stringer - uhop/stream-json GitHub Wiki

This is a JSONC stringer that converts a token stream (including whitespace and comment tokens from the JSONC Parser) back into JSONC text.

Base tokens are handled identically to Stringer. Whitespace and comment tokens are output verbatim.

Introduction

const {chain} = require('stream-chain');
const {parser: jsoncParser} = require('stream-json/jsonc/parser.js');
const {stringer: jsoncStringer} = require('stream-json/jsonc/stringer.js');

const fs = require('fs');

const pipeline = chain([fs.createReadStream('settings.jsonc'), jsoncParser(), jsoncStringer()]);

let result = '';
pipeline.on('data', chunk => (result += chunk));
pipeline.on('end', () => console.log(result));

API

jsoncStringer(options)

The factory function. Returns a flushable function for use in chain():

const {chain} = require('stream-chain');
const {parser: jsoncParser} = require('stream-json/jsonc/parser.js');
const {stringer: jsoncStringer} = require('stream-json/jsonc/stringer.js');

const fs = require('fs');

const pipeline = chain([fs.createReadStream('settings.jsonc'), jsoncParser(), jsoncStringer()]);

let result = '';
pipeline.on('data', chunk => (result += chunk));
pipeline.on('end', () => console.log(result));

Options

All standard Stringer options are supported:

  • useValues, useKeyValues, useStringValues, useNumberValues
  • makeArray

Static methods and properties

jsoncStringer.stringer(options)

Alias of the factory function.

jsoncStringer.asStream(options)

Returns a Duplex stream (object-mode writable, text-mode readable):

const jsoncParser = require('stream-json/jsonc/parser.js');
const jsoncStringer = require('stream-json/jsonc/stringer.js');
const fs = require('fs');

const pipeline = fs.createReadStream('settings.jsonc').pipe(jsoncParser.asStream()).pipe(jsoncStringer.asStream());

let result = '';
pipeline.on('data', chunk => (result += chunk));
pipeline.on('end', () => console.log(result));

Round-tripping

When used with the JSONC parser, the stringer preserves whitespace and comments. Commas and colons are auto-inserted by the stringer, so their exact placement may differ from the original. Trailing commas are normalized away.

const {chain} = require('stream-chain');
const {parser: jsoncParser} = require('stream-json/jsonc/parser.js');
const {stringer: jsoncStringer} = require('stream-json/jsonc/stringer.js');
const {Readable} = require('node:stream');

const input = '{\n  // name\n  "a": 1\n}';
const pipeline = chain([Readable.from([input]), jsoncParser(), jsoncStringer()]);

let result = '';
pipeline.on('data', chunk => (result += chunk));
pipeline.on('end', () => console.log(result));
// Comments and whitespace are preserved in the output