# @fgv/ts-json

> Typescript utilities for working with JSON

Latest version **5.0.2** (published 2025-12-17) · MIT license · 0 weekly downloads

## Install

```sh
npm install @fgv/ts-json
pnpm add @fgv/ts-json
yarn add @fgv/ts-json
bun add @fgv/ts-json
```

## Health

**Score 70/100 (B)** — status: stable.

Positive: has types; esm support; no vulnerabilities; has provenance; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 5.0.2 |
| Published | 2025-12-17 |
| First published | 2020-09-15 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 525 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 1 |
| Author | Erik Fortune |
| Maintainers | efortune |
| Keywords | typescript, json |

## Links

- npm: https://www.npmjs.com/package/@fgv/ts-json
- Repository: https://github.com/ErikFortune/fgv
- Homepage: https://github.com/ErikFortune/fgv/tree/main/libraries/ts-json#readme
- Issues: https://github.com/ErikFortune/fgv/issues
- npm.io page: https://npm.io/package/@fgv/ts-json

## Alternatives

- [@mapbox/jsonlint-lines-primitives](https://npm.io/package/@mapbox/jsonlint-lines-primitives.md) — 5.3M weekly downloads
- [reftools](https://npm.io/package/reftools.md) — 3.5M weekly downloads
- [@hey-api/openapi-ts](https://npm.io/package/@hey-api/openapi-ts.md) — 3.5M weekly downloads
- [@mapbox/geojson-rewind](https://npm.io/package/@mapbox/geojson-rewind.md) — 2.4M weekly downloads
- [turbo-stream](https://npm.io/package/turbo-stream.md) — 1.7M weekly downloads

## Recent versions

- 5.0.2 (latest) — 2025-12-17
- 5.1.0-57 (alpha) — 2026-09-23
- 0.4.3 (lagest) — 2020-11-05
- 5.1.0-56 — 2026-09-20
- 5.1.0-55 — 2026-08-24
- 5.1.0-54 — 2026-08-23
- 5.1.0-53 — 2026-08-22
- 5.1.0-52 — 2026-08-22
- 5.1.0-51 — 2026-08-18
- 5.1.0-50 — 2026-08-16
- 5.1.0-49 — 2026-08-14
- 5.1.0-48 — 2026-08-13
- 5.1.0-47 — 2026-08-07
- 5.1.0-46 — 2026-08-01
- 5.1.0-45 — 2026-07-28
- … 155 more at https://npm.io/package/@fgv/ts-json/versions

## README

<div align="center">
  <h1>ts-json</h1>
  Typescript Utilities for JSON
</div>

<hr/>

## Summary

Assorted JSON-related typescript utilities that I'm tired of copying from project to project. 

---
- [Summary](#summary)
- [Installation](#installation)
- [Overview](#overview)
  - [Type-Safe JSON](#type-safe-json)
  - [Templated JSON](#templated-json)
    - [Multivalue Property Expansion](#multivalue-property-expansion)
  - [Conditional JSON](#conditional-json)
    - [Conditional Match Properties](#conditional-match-properties)
    - [Defined Condition Properties](#defined-condition-properties)
    - [Default Condition Properties](#default-condition-properties)
    - [Flattened Unconditional Blocks](#flattened-unconditional-blocks)
    - [Comments for Uniqueness](#comments-for-uniqueness)
  - [Templating with Conditional JSON](#templating-with-conditional-json)
- [API](#api)
  - [JsonEditor class](#jsoneditor-class)
    - [mergeObjectInPlace method](#mergeobjectinplace-method)
    - [mergeObjectsInPlace method](#mergeobjectsinplace-method)
    - [clone method](#clone-method)
  - [Converters](#converters)
    - [Simple JSON Converter](#simple-json-converter)
    - [Templated JSON Converter](#templated-json-converter)
    - [Conditional JSON Converter](#conditional-json-converter)
## Installation

With npm:
```sh
npm install ts-json
```

## Overview

### Type-Safe JSON
A handful of types express valid JSON as typescript types:
```ts
type JsonPrimitive = boolean | number | string | null;
interface JsonObject { [key: string]: JsonValue }
type JsonValue = JsonPrimitive | JsonObject | JsonArray;
interface JsonArray extends Array<JsonValue> { }
```

### Templated JSON
*Templated JSON* is type-safe JSON, with [mustache](https://www.npmjs.com/package/mustache) template conversions applied to any string properties or keys using a supplied context.
```ts
    const src = {
        '{{prop}}': '{{value}}',
        literalValue: 'literal',
    };

    const result = JsonConverters.templatedJson({ prop: 'someProp', value: 'some value' }).convert(src);
    // result.value is {
    //    someProp: 'some value',
    //    litealValue: 'literal',
    // }
```

#### Multivalue Property Expansion
In a templated JSON object, a key of the form ```*name=value1,value2...``` or ```"[[name]]=value1,value2,...``` is expanded to multiple values, one per item in the comma-separated list that follows the equals sign. The individual values are generated by resolving the property value with a context that includes a variable with the name specified and each of the values in the comma separated list, in turn.  For ```*``` expansion the result is a property named for the variable with an array of all values.  For ```[[``` expansion, the result is one property per value, where the property name matches the input value. For example:
```ts
    // with context:
    const context = {
        properties: ['first', 'second', 'third'],
    };

    // templated conversion of:
    const src = {
        '*prop={{properties}}': {
            '{{prop}}Prop': '{{prop}} value',
        },
        '[[prop]]={{properties}}': {
            '{{prop}}Prop': '{{prop}} value',
        },
    };

    // yields
    const expected = {
        first: {
            firstProp: 'first value',
        },
        second: {
            secondProp: 'second value',
        },
        third: {
            thirdProp: 'third value',
        },
        prop: ['first value', 'second value', 'third value'],
    };
```

The converter options for templated JSON allow for an override of the function that derives the context for each of the children, so it is possible to write a custom derivation function which sets different or additional values based on the
value passed in.

### Conditional JSON

*Conditional JSON* is *templated JSON*, but property names beginning with '?' reperesent conditional properties.

The value of any conditional property must be a JSON object. If the condition is satisfied, (a deep copy of) the children of the conditional property value are merged into the parent object. If the condition is not satisfied, the body is ignored.

#### Conditional Match Properties
Conditional match properties are identified by names with one of these forms:
```ts
    '?value1=value2'
    '?value1>=value2'
    '?value1<=value2'
    '?value1!=value2'
    '?value1>value2'
    '?value1<value2'
```
Where *value1* and *value2* are strings that do not include any of the valid operators. The condition is satisfied if *value2* and *value2* match according to the operator. For example:
```ts
    {
        '?someValue=someValue': {
            conditional1: 'conditional value 1',
        },
        '?someValue=someOtherValue': {
            conditional2: 'conditional value 2',
        },
        '?3>1': {
            conditional3: '3 is greater than 1',
        },
        '?3<1': {
            conditional4: 'this is wrong',
        },
        unconditional: true,
    }
    // yields
    {
        conditional1: 'conditional value 1',
        conditional3: '3 is greater than 1',
        unconditional: true,
    }
```

#### Defined Condition Properties
Defined condition properties are identified by names of the form:
```ts
    '?value'
```
Where *value* is any string, including the empty string.  The condition is satisfied if *value* is not-empty or whitespace. For example:
```ts
    {
        '?someValue': {
            conditional: 'conditional value',
        },
        unconditional: 'unconditional value',
    }
    // yields
    {
        conditional: 'condtional value',
        unconditional: 'unconditional value',
    }
```
but
```ts
    {
        '?': {
            conditional: 'conditional value',
        },
        unconditional: 'unconditional value',
    }
    // yields
    {
        unconditional: 'unconditional value',
    }
```

#### Default Condition Properties
The special conditional property *'?default'* is satisfied if none of the immediately preceding conditional properties match, otherwise it is omitted.  For example:
```ts
    {
        '?someValue=someOtherValue': {
            conditional1: 'conditional value 1',
        },
        '?default': {
            conditional1: 'default conditional value',
        }
    }
    // yields
    {
        conditional1: 'default conditional value',
    }
```
but
```ts
    {
        '?someValue=someValue': {
            conditional1: 'conditional value 1',
        },
        '?default': {
            conditional1: 'default conditional value',
        }
    }
    // yields
    {
        conditional1: 'conditional value 1',
    }
```

#### Flattened Unconditional Blocks
A default value is ignored if any conditional property in the same object was matched. To allow grouping of related conditional values with defaults, the conditional processor also supports
unconditional properties with the '!' prefix.  Any unconditional object properties are flattened and omitted.  For example:
```ts
    {
        '!block1': {
            '?val1=val2': {
                gotVal1: 'match',
            },
            '?default': {
                gotVal1: 'default',
            }
        },
        '!block2': {
            '?val2=val3': {
                gotVal2: 'match',
            },
            '?default': {
                gotVal2: 'default',
            }
        },
    }
    // yields
    {
        gotVal1: 'default',
        gotVal2: 'default',
    }
```

#### Comments for Uniqueness
In any conditional property name, anything that follows the first '#' character is ignored. This makes it possible to include multiple conditions that match the same value. For example:
```ts
    {
        '?this=this': {
            conditional: 'conditional 1',
        },
        unconditional: 'unconditional',
        '?this=this': {
            conditional: 'conditional 2'
        }
    }
```
is not valid JSON, because two properties have the same name, but:
```ts
    {
        '?this=this#1': {
            conditional: 'conditional 1',
        },
        unconditional: 'unconditional',
        '?this=this#2': {
            conditional: 'conditional 2'
        }
    }
    // is valid, and yields:
    {
        unconditional: 'unconditional',
        conditional: 'conditional 2',
    }
```

### Templating with Conditional JSON
Combined with [mustache](https://www.npmjs.com/package/mustache) templating, this conditional syntax allows simple and powerful generation or consumption of conditional JSON files.  For example, consider:
```ts
    {
        userName: '{{user}}',
        password: '{{pw}}',
        '?{{userType}}=admin': {
            rights: '...' // rights for admin
        },
        '?{{userType}}=bot': {
            rights: '...' // rights for bot
        }
        '?{{default}}': {
            rights: '...' // rights for normal user
        },
        '?{{externalId}}': {
            externalId: '{{externalId}}',
        }
    }
```
Given the context:
```ts
    {
        user: 'fred',
        pw: 'freds password',
        userType: 'admin',
        externalId: 'freds SSO credentials',
    }
```
Our example yields:
```ts
    {
        userName: 'fred',
        password: 'freds password',
        rights: '...', // rights for admin
        externalId: 'freds SSO credentials',
    }
```
But given the context:
```ts
    {
        user: 'r2d2',
        password: 'r2s pw',
        userType: 'bot',
    }
```
We get:
```ts
    {
        userName: 'r2d2',
        password: 'r2s pw',
        rights: '...', // rights for bot
    }
```

## API

### JsonEditor class
The *JsonEditor* can be used to edite JSON objects in place or to clone any JSON value,
applying a default context and optional set of editor rules (e.g. for templating, conditional,
multi-value or reference processing) to be applied.

#### mergeObjectInPlace method
The *mergeObjectInPlace* function takes a base object an object to be merged and updates the supplied base object with values from the merge object.  For example:
```ts
    const base = {
        property1: 'value 1',
        property2: 'value 2',
    };
    const merge = {
        property2: 'value 2A',
        property3: 'value 3A',
    };
    const result = editor.mergeObjectInPlace(base, merge);
    // updates the base object and returns success with base object, which means
    // that both base and result.value have the shape:
    {
        property1: 'value 1',
        property2: 'value 2A',
        property3: 'value 3A',
    }
```

#### mergeObjectsInPlace method
The *mergeObjectsInPlace* function takes a base object and one or more objects to be merged, and updates the base object with values from each of the merge objects in the order supplied.  for example:
```ts
    const base = {
        property1: 'value 1',
        property2: 'value 2',
    };
    const mergeA = {
        property2: 'value 2A',
        property3: 'value 3A',
    };
    const mergeB = {
        property3: 'value 3B',
        property4: 'value 4B',
    };
    const result = editor.mergeObjectsInPlace(base, mergeA, mergeB);
    // updates the base object and returns success with base object, which means
    // that both base and result.value have the shape:
    {
        property1: 'value 1',
        property2: 'value 2A',
        property3: 'value 3B',
        property4: 'value 4B',
    }
```

#### clone method
The *clone* method deep clones a supplied JSON value, applying all editor rules and
a default or optionally supplied context.

### Converters

A convenience set of [ts-utils *Converters*](https://github.com/DidjaRedo/ts-utils/blob/master/README.md) and generators for the most common JSON conversions.

#### Simple JSON Converter

Use the *json* converter to convert unknown to type-safe JSON. Fails if the value to be converted is not valid JSON.
```ts
    import * as JsonConverters from '@fgv/ts-json/converters';

    const result = JsonConverters.json.convert(someUnknown);
    if (result.isSuccess()) {
        // someUnknown was valid JSON
        // jsonResult.value is a JsonValue deep copy of someUnknown
    }
    else {
        // someUnknown was not valid JSON
        // jsonResult.message describes the error
    }
```

#### Templated JSON Converter

Use the *templatedJson* converter to convert unknown to type-safe JSON, applying [mustache](https://www.npmjs.com/package/mustache) template conversions to any string properties or keys using the supplied context.
```ts
    const src = {
        '{{prop}}': '{{value}}',
        literalValue: 'literal',
    };

    const result = JsonConverters.templatedJson({ prop: 'someProp', value: 'some value' }).convert(src);
    // result.value is {
    //    someProp: 'some value',
    //    litealValue: 'literal',
    // }
```

#### Conditional JSON Converter

Use the *conditionalJson* converter to convert unknown to type-safe JSON, applying [mustache](https://www.npmjs.com/package/mustache) template conversions to any string properties or keys using the supplied context *and* merging or omitting conditional properties as appropriate.  For example:
```ts
    const config =     {
        userName: '{{user}}',
        password: '{{pw}}',
        '?{{userType}}=admin': {
            rights: '...' // rights for admin
        },
        '?{{userType}}=bot': {
            rights: '...' // rights for bot
        }
        '?{{default}}': {
            rights: '...' // rights for normal user
        },
        '?{{externalId}}': {
            externalId: '{{externalId}}',
        }
    };
    const context =     {
        user: 'fred',
        pw: 'freds password',
        userType: 'admin',
        externalId: 'freds SSO credentials',
    };

    const result = JsonConverters.conditionalJson(context).convert(config);
    // succeeds and yields
    {
        userName: 'fred',
        password: 'freds password',
        rights: '...', // rights for admin
        externalId: 'freds SSO credentials',
    }
```

---
_Source: https://npm.io/package/@fgv/ts-json · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
