Edit JSON text in-place for a minimal diff

Overview

npm version downloads build status coverage status Language grade: JavaScript

edit-json

Edit a textual JSON (not a JavaScript object) for a minimal diff, either programatically or by applying a JSON Patch (RFC6902).

When serializing the result down to a string, it'll resemble the source JSON as much as possible with regards to property order, whitespace (indentation) and flow types (arrays and objects on one line).

Editing JSON is easy, just JSON.parse() and play around, then JSON.stringify(). To apply a JSON Patch, there are several packages out there.

This package focuses not on working with JSON as a JavaScript object, but as its textual representation. The package parses the JSON string (as e.g. from a file) as tokens, builds up a logical representation of it, and then applies transformations to that representation. Whitespace (tabs, spaces) as well as multi-line or single-line arrays/objects are remembered.

To do the same with YAML, check out yaml-diff-patch.

Example

Given:

{
    "x": "non-alphanumerically ordered properties, obviously",
    "foo": [ "same", "line", "array" ],
    "bar": {
        "some": "object"
    }
}

Applying the JSON Patch:

[ {
    "op": "move",
    "from": "/foo",
    "path": "/bar/herenow"
} ]

Produces:

{
    "x": "non-alphanumerically ordered properties, obviously",
    "bar": {
        "herenow": [ "same", "line", "array" ],
        "some": "object"
    }
}

Properties aren't re-ordered ("x" is still first), but by default, it will try to insert properties orderly, such as when creating "herenow" in "bar". It'll be added before "some", "h" < "s". This is done with a best effort, since it's not always possible (the object might have unordered properties).

Note also that the array is not split into multiple lines, which would happen with default JSON.stringify (unless the whole document is one line of course). The source format is kept if possible.

Install

npm i edit-json or yarn add edit-json

This is a pure ESM package, and requires Node.js >=14.13.1

Simple usage

Exports

The package exports parseJson (to be documented) and jsonPatch.

Definition

jsonPatch( json: string, operations: Operations[], options: Options ): string

Applies a list of JSON Patch operations to the source json and returns the new json string.

The options are:

  • whitespace ('auto' | 'tabs' | number): Specifies whitespace strategy. Defaults to 'auto'. Force tabs using 'tabs' or spaces using number (e.g. 2 or 4).
  • ordered (boolean): Try to insert new properties in order.

RFC6902

By the spec RFC6902, the path property of an operation (and the from in move and copy operations) must be a well-formed JSON Pointer, with encoded path segments. jsonpos exposes helpers for this.

To be more practical for programmatic usage, this package allows not only JSON Pointer strings as paths, but also arrays of (raw unencoded) strings. So you can use e.g. "/foo/bar" or ["foo", "bar"], whichever you prefer. For path segments containing e.g. a slash, it would be "/f~1o~1o/bar" or ["f/o/o", "bar"].

You might also like...

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics.

Gatsby-starter-minimal-blog - Typography driven, feature-rich blogging theme with minimal aesthetics. Includes tags/categories support and extensive features for code blocks such as live preview, line numbers, and line highlighting.

Jan 29, 2022

Json-parser - A parser for json-objects without dependencies

Json Parser This is a experimental tool that I create for educational purposes, it's based in the jq works With this tool you can parse json-like stri

Jan 3, 2022

Pretty-print-json - 🦋 Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

Pretty-print-json - 🦋 Pretty-print JSON data into HTML to indent and colorize (written in TypeScript)

pretty-print-json Pretty-print JSON data into HTML to indent and colorize (written in TypeScript) 1) Try It Out Interactive online tool to format JSON

Dec 30, 2022

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Jan 4, 2023

JSON Struct is a vocabulary that allows you to annotate and validate JSON documents.

JSON-Struct JSON Struct is a vocabulary that allows you to annotate and validate JSON documents. Examples Basic This is a simple example of vocabulary

May 8, 2022

Prisma 2+ generator to emit a JSON file that can be run with json-server

Prisma 2+ generator to emit a JSON file that can be run with json-server

Prisma JSON Server Generator A Prisma generator that automates creating a JSON file that can be run as a server from your Prisma schema. Explore the o

Jan 7, 2023

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Dec 6, 2022

✏️ A small jQuery extension to turn a static HTML table into an editable one. For quickly populating a small table with JSON data, letting the user modify it with validation, and then getting JSON data back out.

jquery-editable-table A small jQuery extension to turn an HTML table editable for fast data entry and validation Demo 👉 https://jsfiddle.net/torrobin

Jul 31, 2022

Add aliasing support to Vite from tsconfig.json or jsconfig.json files

Config to Alias Config to Alias adds aliasing support to Astro, JavaScript, TypeScript, and CSS files. Usage Install Config to Alias. npm install @ast

Mar 17, 2023
Comments
  • The automated release is failing 🚨

    The automated release is failing 🚨

    :rotating_light: The automated release from the master branch failed. :rotating_light:

    I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

    You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

    Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

    Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

    If you are not sure how to resolve this, here are some links that can help you:

    If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


    No npm token specified.

    An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

    Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


    Good luck with your project ✨

    Your semantic-release bot :package::rocket:

    semantic-release 
    opened by github-actions[bot] 0
Releases(v1.2.1)
Owner
Gustaf Räntilä
Gustaf Räntilä
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Reddit Place Tracer is a browser based userscript for the 2022 Reddit /r/Place project

Reddit Place Tracer is a browser based userscript for the 2022 Reddit /r/Place project which adds a transparent image on top of the canvas to aid communities with drawing the same image. It shows how the canvas should look, where each pixel goes, and what color. The user must manually click on these spots. It is not an automated bot and does not break any rules.

null 3 Apr 3, 2022
OnePiece /r/place repo to store the template and script for outlining the place to put titles

onepiece-place OnePiece /r/place repo to store the template and script for outlining the place to put titles This script & repo are cloned from Antice

Lopeh 11 Apr 9, 2022
The /r/place Atlas is a project aiming to catalog all the artworks created during Reddit's 2022 /r/place event.

The 2022 Place Atlas The /r/place Atlas is a project aiming to catalog all the artworks created during Reddit's 2022 /r/place event. This project was

Place Atlas 397 Dec 28, 2022
JCS (JSON Canonicalization Scheme), JSON digests, and JSON Merkle hashes

JSON Hash This package contains the following JSON utilties for Deno: digest.ts provides cryptographic hash digests of JSON trees. It guarantee that d

Hong Minhee (洪 民憙) 13 Sep 2, 2022
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
Get a diff view of your Obsidian Sync, File Recovery and Git version history

Version History Diff (for Sync and File Recovery Core plugins and Git) Note This plugin uses private APIs, so it may break at any time. Use at your ow

null 39 Dec 26, 2022
🔐 A Privacy-first Diff tool for everyone. ✅ Your data never hits our servers.

Features ?? Privacy-first developer tool. ?? Run on your Web Browser, Your data is sent nowhere. ?? Find a Difference between two text input for Side

Proxyman 41 Dec 5, 2022
Google-reviews-crawler - A simple Playwright crawler that stores Google Maps Place/Business reviews to a JSON file.

google-reviews-crawler A simple Playwright crawler that stores Google Maps Place/Business reviews to a JSON file. Usage Clone the repo, install the de

￸A￸l￸e￸x D￸o￸m￸a￸k￸i￸d￸i￸s 6 Oct 26, 2022