0.6.0 • Published 6 months ago

json-sculpt v0.6.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

JSON Sculpt

JSON Sculpt is a utility library designed to transform or "sculpt" JSON objects into your desired shape.

Table of Contents

  1. Installation
  2. Usage
  3. API

Installation

npm install json-sculpt

Usage

import { sculptJson, JsonObject, JsonValue } from "json-sculpt";

const json: JsonObject = {
    name: "Brennan",
    age: 30,
    address: {
        city: "San Francisco",
    },
    {$sculpt$}: {
        name: "{{this.name}}",
        description: "The average age of {{self.address.city}} is {{state.averageAge}}"
    },
};

const state = {
    averageAge: 40,
};

const result = sculptJson<undefined>(json, state);
console.log(result); // { name: "Brennan", description: "The average age of San Francisco is 40" }

API

sculptJson

Transforms a JSON object into a desired shape.

Parameters:

  • json (JsonObject): The JSON object to be transformed.
  • replacements (Replacements): An object containing custom values to use during sculpting. The values can be either primitives or functions that return primitives. If a function is used, it will be called with the root JSON object as its only argument.
  • options (SculptOptions): An object containing options for transforming the JSON.

Options:

  • onlyResolveSculpt (bool): Should only commands nested under a {$sculpt$} object should be resolved, or all values in the JSON object?
  • throwOnError (bool): Should an error should be thrown if sculpting fails?

Returns:

The sculpted JSON object. If a Result type is provided as a generic parameter, the function will return the specified type.

sculptString

Replaces all {{}}-enclosed keys with matching values from a state object.

Parameters:

  • template (string): The string to sculpt.
  • replacements (Replacements): Object containing replacment values to replace {{}}-enclosed keys.

Returns:

The sculpted string.

findObjectInJson

Searches for the first object that matches the provided matcher within a JSON structure.

Parameters:

  • json (JsonObject): JSON object within which to perform the search.
  • matcher (JsonObject): JSON object used to match objects within the provided JSON structure.

Returns:

The first matched JSON object, or undefined if no match is found.

replaceObjectInJson

Replaces matched objects within a JSON structure with a specified replacement object.

Parameters:

  • json (JsonValue): JSON object within which to perform the replacement.
  • replacements (JsonObject): Object that will replace matched objects.
  • matcher (JsonObject): JSON object used to match objects within the provided JSON structure.

Returns:

JSON object with all matched objects replaced with the replacement object.

0.6.0

6 months ago

0.3.0

12 months ago

0.5.0

11 months ago

0.4.1

11 months ago

0.3.2

12 months ago

0.4.0

11 months ago

0.3.1

12 months ago

0.2.0

1 year ago

0.1.0

1 year ago