Patch JSON
Patch JSON is utility and YAML-based language to make changes over JSON and produce new updated JSON.
Contents
- Introduction
- Getting started
- Usage
- Actions
- API
- References
Introduction
You can use few approaches to reach element from JSON object.
-
Dot notation. This approach is recommended only for simple cases, that don't require any expressions. For instance:
- Getting menu title: component.menu.title
- Getting "open" item of menu: component.menu.items[0]
-
JSONPath notation. More powerfull notation that allows us to use expressions to get element:
- Getting menu title: $.component.menu.title
- Getting "open" item of menu: $.component.menu.items[?(@.id === 'open')]
Common patch structure:
component.menu.title: - ACTION: <ACTION NAME> [ VALUE: <VALUE> ] - ACTION: <ACTION NAME> component.menu: - ACTION: <ACTION NAME> [ VALUE: <VALUE> ] - ACTION: <ACTION NAME>
This structure defines sequence of actions that should applied to json.
Getting started
Instal json-patch into the project:
npm install patch-json --save
or
yarn add patch-json
Usage
Let's take a look at example of patch-json usage:
const fs = ;const jsonPatch = ; let jsonContent = fs;let patch = fs;// Apply patch to loaded json data:let newJson = jsonPatch;
Common actions
SET
Add new or modify exists node of the JSON object.
Parameters
- ACTION: SET
- VALUE - {any} New value
component.menu: - ACTION: SET VALUE: newProperty: prop1: value1
UNSET
Remove node from JSON object
Parameters
- ACTION: UNSET
component.menu.title: - ACTION: REMOVE
Array actions
These actions can be applied only to the arrays.
PUSH
Append new item to the end of an array
Parameters
- ACTION: PUSH
- VALUE - {any} New value
component: - ACTION: PUSH VALUE: newProperty: prop1: value1
UNSHIFT
Add item to the beginning of an array
Parameters
- ACTION: UNSHIFT
- VALUE - {any} New value
component: - ACTION: UNSHIFT VALUE: newProperty: prop1: value1
INSERT
Insert item into array
Parameters
- ACTION: INSERT
- [AFTER] or [BEFORE] : {String} JSONPath value
- VALUE: {any} inserted value
components: - ACTION: INSERT AFTER: "[?(@.id === 'search')]" VALUE: id: 'delete' - ACTION: INSERT BEFORE: "[?(@.id === 'results')]" VALUE: id: 'users'
DELETE
Delete item from array
Parameters
- ACTION: DELETE
- ITEM: {String} JSONPath value
components: - ACTION: DELETE ITEM: "[?(@.id === 'search')]"
API
Methods
patch(jsonString, yamlString) -> Object
validate(yamlString) -> Boolean
Errors
Patch JSON uses exceptions to process errors. Error object contains name property that defines error type:
- JSON_VALIDATION_ERROR
- YAML_VALIDATION_ERROR
- YAML_STRUCTURE_ERROR
- PATCH_ERROR
Also it contains message and stack properties to get additional info about error.
try jsonPath catchex if exname === 'JSON_VALIDATION_ERROR' else if exname === 'YAML_VALIDATION_ERROR' else if exname === 'YAML_STRUCTURE_ERROR' else if exname === 'PATCH_ERROR'
References
- JSONPath syntax description