Skip to content

English__Data Sources__JSON

Ramirez Vargas, José Pablo edited this page Nov 7, 2024 · 3 revisions

JSON Data Source

wj-config provides the JSON data source that allows JSON strings to be specified as configuration data sources.

The parsing is done using the native JSON object, but this can be changed.

How To Use the JSON Data Source

As with all other data sources, there is a specialized addJson() method in the configuration builder that assists with this job. This function defines three parameters in the form of 1 overload:

addJson<NewT extends Record<string, any>>(
    json: string | (() => Promise<string>),
    jsonParser?: IJsonParser<NewT>,
    reviver?: (this: any, key: string, value: any) => any
): IBuilder<MergeResult<T, NewT>>;
  1. The first one is the JSON string or a function that returns the JSON string.
  2. The second one is the object that provides parsing. It must provide the parse() function and must accept a reviver function, just like the built-in JSON parser.
  3. Optional reviver function that is passed to the JSON parser.

As with other data sources, the main data parameter accepts a function. This function approach is the recommended approach when doing any form of conditional configuration if obtaining the JSON text will incur in potentially-wasted CPU cycles or RAM.

The second parameter is meant to provide a parser object such as the popular JSON5 parser that allows things like trailing commas and comments in the JSON text.

The third parameter is a reviver function. This function is not explained here. This is supported by the built-in JSON and the JSON5 objects. Refer to their documentation for further information.

This is how one would use JSON5:

import JSON5 from 'json5';
...
const config = await wjConfig()
    .addJson('{ "propA": "string value", "propB": 123, }', JSON5)
    ...
    .build();

Data Requirements

The only requirement is that the provided data be a string that represents an object in JSON (JavaScript Object Notation), or whatever format/variant the provided parser supports. See the external documentation of the reviver function for any additional requirements.