• Stars
    star
    1,060
  • Rank 41,897 (Top 0.9 %)
  • Language
    CoffeeScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Structural diff for JSON files

JSON structural diff

Does exactly what you think it does:

Screenshot

Installation

    npm install -g json-diff

Contribution policy

  1. This project is maintained thanks to your contributions! Please send pull requests.

  2. I will merge any pull request that adds something useful, does not break existing things, has reasonable code quality and provides/updates tests where appropriate.

  3. Anyone who gets a significant pull request merged gets commit access to the repository.

Usage

Simple:

    json-diff a.json b.json

Detailed:

    % json-diff --help

    Usage: json-diff [-vCjfonskKp] first.json second.json

    Arguments:
    <first.json>          Old file
    <second.json>         New file

    General options:
    -v, --verbose         Output progress info
    -C, --[no-]color      Colored output
    -j, --raw-json        Display raw JSON encoding of the diff
    -f, --full            Include the equal sections of the document, not just the deltas
        --max-elisions COUNT  Max number of ...s to show in a row in "deltas" mode (before
                                collapsing them)

    -o, --output-keys KEYS  Always print this comma separated keys, with their value, if they are
                            part of an object with any diff

    -x, --exclude-keys KEYS  Exclude these comma separated keys from comparison on both files

    -n, --output-new-only   Output only the updated and new key/value pairs (without marking them as
                            such). If you need only the diffs from the old file, just exchange the
                            first and second json.

    -s, --sort            Sort primitive values in arrays before comparing
    -k, --keys-only       Compare only the keys, ignore the differences in values
    -K, --keep-unchanged-values   Instead of omitting values that are equal, output them as they are
    -p, --precision DECIMALS  Round all floating point numbers to this number of decimal places prior
                                to comparison

    -h, --help            Display this usage information

In javascript (ES5):

var jsonDiff = require('json-diff');

console.log(jsonDiff.diffString({ foo: 'bar' }, { foo: 'baz' }));
// Output:
//  {
// -  foo: "bar"
// +  foo: "baz"
//  }

// As above, but without console colors
console.log(jsonDiff.diffString({ foo: 'bar' }, { foo: 'baz' }, { color: false }));

// Raw output:
console.log(jsonDiff.diff({ foo: 'bar', b: 3 }, { foo: 'baz', b: 3 }));
// Output:
// { foo: { __old: 'bar', __new: 'baz' } }

// Passing in the "full" option:
console.log(jsonDiff.diff({ foo: 'bar', b: 3 }, { foo: 'baz', b: 3 }, { full: true }));
// Output:
// { foo: { __old: 'bar', __new: 'baz' }, b: 3 }

In javascript (ES6+):

import { diffString, diff } from 'json-diff';

console.log(diffString({ foo: 'bar' }, { foo: 'baz' }));
console.log(diff({ foo: 'bar' }, { foo: 'baz' }));

Features

  • colorized, diff-like output
  • fuzzy matching of modified array elements (when array elements are object hierarchies)
  • "keysOnly" option to compare only the json structure (keys), ignoring the values
  • "full" option to output the entire json tree, not just the deltas
  • "outputKeys" option to always output the given keys for an object that has differences
  • reasonable test coverage (far from 100%, though)

Output Language in Raw-json mode ("full" mode)

ARRAYS

Unless two arrays are equal, all array elements are transformed into 2-tuple arrays:

  • The first element is a one character string denoting the equality ('+', '-', '~', ' ')
  • The second element is the old (-), new (+), altered sub-object (~), or unchanged (' ') value
    json-diff.js --full --raw-json <(echo '[1,7,3]') <(echo '[1,2,3]')
         [ [ " ", 1 ], [ "-", 7 ], [ "+", 2 ], [ " ", 3 ] ]
    json-diff.js --full --raw-json <(echo '[1,["a","b"],4]') <(echo '[1,["a","c"],4]')
         [ [ " ", 1 ], [ "~", [ [ " ", "a" ], [ "-", "b" ], [ "+", "c" ] ] ], [ " ", 4 ] ]
  • If two arrays are equal, they are left as is.

OBJECTS

Object property values:

  • If equal, they are left as is
  • Unequal scalar values are replaced by an object containing the old and new value:
    json-diff.js --full  --raw-json <(echo '{"a":4}') <(echo '{"a":5}')
        { "a": { "__old": 4, "__new": 5 } }
  • Unequal arrays and objects are replaced by their diff:
    json-diff.js --full  --raw-json <(echo '{"a":[4,5]}') <(echo '{"a":[4,6]}')
        { "a": [ [ " ", 4 ], [ "-", 5 ], [ "+", 6 ] ] }

Object property keys:

  • Object keys that are deleted or added between two objects are marked as such:
    json-diff.js --full  --raw-json <(echo '{"a":[4,5]}') <(echo '{"b":[4,5]}')
        { "a__deleted": [ 4, 5 ], "b__added": [ 4, 5 ] }
    json-diff.js --full  --raw-json <(echo '{"a":[4,5]}') <(echo '{"b":[4,6]}')
        { "a__deleted": [ 4, 5 ], "b__added": [ 4, 6 ] }

Non-full mode

  • In regular, delta-only (non-"full") mode, equal properties and values are omitted:
    json-diff.js --raw-json <(echo '{"a":4, "b":6}') <(echo '{"a":5,"b":6}')
        { "a": { "__old": 4, "__new": 5 } }
  • Equal array elements are represented by a one-tuple containing only a space " ":
    json-diff.js --raw-json <(echo '[1,7,3]') <(echo '[1,2,3]')
        [ [ " " ], [ "-", 7 ], [ "+", 2 ], [ " " ] ]

Tests

Run:

    npm test

Output:

Open to View Test Output 🔽
[email protected] test
coffee -c test; mocha test/*.js

colorizeToArray ✔ should return ' ' for a scalar value ✔ should return ' ' for 'null' value ✔ should return ' ' for 'false' value ✔ should return '-', '+' for a scalar diff ✔ should return '-', '+' for 'null' and 'false' diff ✔ should return '-: ' for an object diff with a removed key ✔ should return '+: ' for an object diff with an added key ✔ should return '+: ' for an object diff with an added key with 'null' value ✔ should return '+: ' for an object diff with an added key with 'false' value ✔ should return '+: ' for an object diff with an added key and a non-scalar value ✔ should return ' : ' for an object diff with a modified key ✔ should return '+' for an array diff ✔ should return '-' for an array diff ✔ should handle an array diff with subobject diff ✔ should collapse long sequences of identical subobjects into one '...'

colorize ✔ should return a string with ANSI escapes ✔ should return a string without ANSI escapes on { color: false }

diff with simple scalar values ✔ should return undefined for two identical numbers ✔ should return undefined for two identical strings ✔ should return { __old: , __new: } object for two different numbers with objects ✔ should return undefined for two empty objects ✔ should return undefined for two objects with identical contents ✔ should return undefined for two object hierarchies with identical contents ✔ should return { __deleted: } when the second object is missing a key ✔ should return { __added: } when the first object is missing a key ✔ should return { : { __old: , __new: } } for two objects with different scalar values for a key ✔ should return { : } with a recursive diff for two objects with different values for a key with arrays of scalars ✔ should return undefined for two arrays with identical contents ✔ should return [..., ['-', ], ...] for two arrays when the second array is missing a value ✔ should return [..., ['+', ], ...] for two arrays when the second one has an extra value ✔ should return [..., ['+', ]] for two arrays when the second one has an extra value at the end (edge case test) with arrays of objects ✔ should return undefined for two arrays with identical contents ✔ should return undefined for two arrays with identical, empty object contents ✔ should return undefined for two arrays with identical, empty array contents ✔ should return undefined for two arrays with identical array contents including 'null' ✔ should return undefined for two arrays with identical, repeated contents ✔ should return [..., ['-', ], ...] for two arrays when the second array is missing a value ✔ should return [..., ['+', ], ...] for two arrays when the second array has an extra value ✔ should return [['+', ], ..., ['+', ]] for two arrays containing objects of 3 or more properties when the second array has extra values (fixes issue #57) ✔ should return [..., ['+', ], ...] for two arrays when the second array has a new but nearly identical object added ✔ should return [..., ['~', ], ...] for two arrays when an item has been modified with reported bugs ✔ should handle type mismatch during scalarize ✔ should handle mixed scalars and non-scalars in scalarize

diff({sort: true}) with arrays ✔ should return undefined for two arrays with the same contents in different order

diff({keepUnchangedValues: true}) with nested object ✔ should return partial object with modified and unmodified elements in the edited scope

diff({full: true}) with simple scalar values ✔ should return the number for two identical numbers ✔ should return the string for two identical strings ✔ should return { __old: , __new: } object for two different numbers with objects ✔ should return an empty object for two empty objects ✔ should return the object for two objects with identical contents ✔ should return the object for two object hierarchies with identical contents ✔ should return { __deleted: , } when the second object is missing a key ✔ should return { __added: , } when the first object is missing a key ✔ should return { : { __old: , __new: } } for two objects with different scalar values for a key ✔ should return { : , } with a recursive diff for two objects with different values for a key ✔ should return { : , } with a recursive diff for two objects with different values for a key with arrays of scalars ✔ should return an array showing no changes for any element for two arrays with identical contents ✔ should return [[' ', ], ['-', ], [' ', ]] for two arrays when the second array is missing a value ✔ should return [' ', ], ['+', ], [' ', ]] for two arrays when the second one has an extra value ✔ should return [' ', s], ['+', ]] for two arrays when the second one has an extra value at the end (edge case test) with arrays of objects ✔ should return an array of unchanged elements for two arrays with identical contents ✔ should return an array with an unchanged element for two arrays with identical, empty object contents ✔ should return an array with an unchanged element for two arrays with identical, empty array contents ✔ should return an array of unchanged elements for two arrays with identical array contents including 'null' ✔ should return an array of unchanged elements for two arrays with identical, repeated contents ✔ should return [[' ', ], ['-', ], [' ', ]] for two arrays when the second array is missing a value ✔ should return [[' ', ], ['+', ], [' ', ]] for two arrays when the second array has an extra value ✔ should return [[' ', ], ['+', ], [' ', ]] for two arrays when the second array has a new but nearly identical object added ✔ should return [[' ', ], ['~', ], [' ', ]] for two arrays when an item has been modified

diff({ outputKeys: foo,bar } ✔ should return keys foo and bar although they have no changes ✔ should return keys foo (with addition) and bar (with no changes) ✔ should return keys foo and bar (with addition) ✔ should return nothing as the entire object is equal, no matter that show keys has some of them ✔ should return the keys of an entire object although it has no changes

diff({keysOnly: true}) with simple scalar values ✔ should return undefined for two identical numbers ✔ should return undefined for two identical strings ✔ should return undefined object for two different numbers with objects ✔ should return undefined for two empty objects ✔ should return undefined for two objects with identical contents ✔ should return undefined for two object hierarchies with identical contents ✔ should return { __deleted: } when the second object is missing a key ✔ should return { __added: } when the first object is missing a key ✔ should return undefined for two objects with different scalar values for a key ✔ should return undefined with a recursive diff for two objects with different values for a key ✔ should return { : } with a recursive diff when second object is missing a key and two objects with different values for a key with arrays of scalars ✔ should return undefined for two arrays with identical contents ✔ should return undefined for two arrays with when an item has been modified ✔ should return [..., ['-', ], ...] for two arrays when the second array is missing a value ✔ should return [..., ['+', ], ...] for two arrays when the second one has an extra value ✔ should return [..., ['+', ]] for two arrays when the second one has an extra value at the end (edge case test) with arrays of objects ✔ should return undefined for two arrays with identical contents ✔ should return undefined for two arrays with identical, empty object contents ✔ should return undefined for two arrays with identical, empty array contents ✔ should return undefined for two arrays with identical, repeated contents ✔ should return [..., ['-', ], ...] for two arrays when the second array is missing a value ✔ should return [..., ['+', ], ...] for two arrays when the second array has an extra value ✔ should return [..., ['~', ], ...] for two arrays when an item has been modified

diffString ✔ should produce the expected result for the example JSON files ✔ should produce the expected result for the example JSON files with precision set to 1 ✔ should produce the expected colored result for the example JSON files ✔ return an empty string when no diff found

diff({ outputNewOnly: true } ✔ should return only new diffs (added) ✔ should return only new diffs (changed) ✔ should return only new diffs (deleted) ✔ should return only old diffs - exchanged first and second json (added) ✔ should return only old diffs - exchanged first and second json (changed) ✔ should return only old diffs - exchanged first and second json (deleted)

107 passing (74ms)

Change Log

  • 1.0.6 Comment out another debugging output.
  • 1.0.5 Comment out debugging output(!)
  • 1.0.4 Fix typo that broke -o/--output-keys
  • 1.0.3 Change from cli-color to colors to reduce package size.
  • 1.0.2 Add colorize and colorizeToCallback to module exports (Fix bug #103)
  • 1.0.1 Bug fixes: Properly compare date objects; properly exclude keys with -x; improve README readability.
  • 1.0.0 Properly distinguish list elements with identical strings of different types e.g. ["true"] vs [true], ["0"] vs [0] (enabled by switching to a new difflib)
  • 0.10.0 Add --exclude-keys
  • 0.9.1 Fix bug #88
  • 0.9.0 Add --output-new-only option
  • 0.8.0 Add --keep-unchanged-values option
  • 0.7.4 Fix bug #76
  • 0.7.3 Revert use of ?? operator in 0.7.2 (which caused a breaking change)
  • 0.7.2 Add --maxElisions and --precision options.
  • 0.7.1 Add --output-keys option.
  • 0.7.0 Add --sort option.
  • 0.6.3 Fix ticket #68.
  • 0.6.2 Provide examples of setting mode from code.
  • 0.6.1 Return exit code 0. Update cli-color to the latest version.
  • 0.6.0 Convert project code to ES6.
  • 0.5.5 Fix bug in scalarize fuzzy compare logic.
  • 0.4.0 Add --keys-only feature.

License

© Andrey Tarantsov. Distributed under the MIT license.

More Repositories

1

SoloComponents-iOS

Self-contained, two-file (.h/.m) iPhone/iPad components that are dead-easy to drop into your projects
Objective-C
571
star
2

ScrollingMadness

A catalog of UIScrollView samples (iPhone)
Objective-C
242
star
3

fsmonitor.js

Cross-platform file system change monitoring for Node.js
CoffeeScript
49
star
4

diff

Quick'n'easy string diffs for Golang, mainly for diffing strings in tests
Go
38
star
5

rlwrap

rlwrap by Hans Lub, imported into Git
C
36
star
6

plist-to-json

A tiny command-line tool to convert (xml) .plist files to JSON format
JavaScript
33
star
7

aidev

AI developer: ask GPT-4 to modify an entire folder full of files
Go
31
star
8

find-fsevents-bugs

C
25
star
9

CheckAppSignature

A tiny tool to check code signature of Mac .app bundles and iOS .app/.ipa files
Shell
24
star
10

cvsps

C
22
star
11

fsmonitor.c

Cross-platform lean file system monitoring library in pure C. Licensed under MIT.
C
22
star
12

git-subdir

A reimplementation of git-subtree that works better for simple workflows. As you might have guessed, it provides a new 'git subdir' command.
Shell
20
star
13

apitree.js

Node.js module to create a SocketStream-style API tree from a file system directory
CoffeeScript
14
star
14

openai

Best way to use ChatGPT/GPT-3 with Go: zero dependencies, tokenizer, under 1500 LOC
Go
13
star
15

majority.js

Master election protocol for master-slave cloud services in Node.js
JavaScript
12
star
16

yoursway-eclipse-osx-repackager

Repackages Eclipse and Rich Client Platform applications as Mac OS X bundles
12
star
17

env

Emacs Lisp
11
star
18

locateimage

Golang library to locate an image inside a larger image (currently implemented for RGBA images only), with optional fuzzy matching
Go
11
star
19

dreamopt.js

Command-line parser with readable syntax from your sweetest dreams
CoffeeScript
9
star
20

hackers-coding-style-guide

Andrey Tarantsov's Coding Style Guide
8
star
21

OCISL

Open Community Indie Software License
8
star
22

funfix

Datastore fixtures the fun way! (Python)
Python
8
star
23

FSEventsFix

Mac OS X library that works around a long-standing bug in realpath() that prevents FSEvents API from monitoring certain folders on a wide range of OS X releases
C
8
star
24

subtitle-tools

A tool for resyncing SRT files
Ruby
8
star
25

pathspec.js

Shell- and .gitignore-style wildcards and file lists
CoffeeScript
7
star
26

yoursway-commons

YourSway Commons
Java
7
star
27

databinding

Eclipse Databinding port to Java 1.5
6
star
28

yoursway-builder

YourSway Builder
Ruby
6
star
29

underscorejs-cheatsheet

User styles for printing Underscore.js web site as a one-page cheatsheet
6
star
30

white

Run from your project folder before committing to Git to avoid whitespace errors
Ruby
5
star
31

platypus

My fork of Platypus (with some bugs fixed)
5
star
32

telegramapi

Work-in-progress MTProto and full Telegram API implementation in Go
Go
5
star
33

xdry

Extra DRY: Objective-C boilerplate autogenerator
Ruby
5
star
34

YSCocoaTouchCommons

Objective-C
5
star
35

kilim-osgi

Kilim port for OSGi environment
Java
4
star
36

git-dep

Git-dep command to handle multiple repositories with dependencies
4
star
37

shell-scripts

A collection of useful shell scripts and my zsh configs
4
star
38

SkypePushToTalk

Push-To-Talk and Mute/Unmute hotkey for Skype (Mac only). UPDATE: use Shush (http://mizage.com/shush/) instead.
C
4
star
39

sqlstruct

Use Go structs with database/sql using this code generator
Go
4
star
40

Sublimacs

A plugin for Sublime Text 2 to make Sublime as good as Emacs for day-to-day text editing operations
Python
4
star
41

retester

re:tester
PHP
3
star
42

ujudge

3
star
43

yoursway-dltk

3
star
44

js2objc

JavaScript to Objective-C transpiler wannabe
CoffeeScript
3
star
45

yoursway-software-update

YourSway Software Update engine
Java
3
star
46

yoursway-swt

YourSway's SWT repository
Java
3
star
47

yoursway-sadr

An unfinished project to implement a great Static Analysis engine in Java. Feel free to reuse under the MIT license. (A legacy of a closed-down company I have owned.)
Java
3
star
48

fseventsmon

C
3
star
49

tarantsov.com

JavaScript
3
star
50

pyjamas

PyJamas, imported from sourceforge subversion repo
Python
3
star
51

better-tender

Improved UI for Tender Support (browser extensions for Safari and Chrome)
CoffeeScript
3
star
52

grunt-typescript-export

Concat .d.ts from multiple files to provide an implicit module declaration for a npm package implemented in TypeScript
JavaScript
3
star
53

yoursway-site

A Google App Engine web site source for a closed-down company I have owned. Feel free to reuse under the MIT license if you will.
Python
3
star
54

yoursway-ide

An unfinished project to implement a TextMate-style IDE in Java/SWT. Feel free to reuse under the MIT license. I don't think it compiles and runs, but parts and components may prove to be useful. (A legacy of a closed-down company I have owned.)
Java
3
star
55

yoursway-ecabu

YourSway Eclipse Application Builder
Ruby
2
star
56

yoursway-modeling

YourSway Modeling Framework
2
star
57

yoursway-sunrise

YourSway Sunrise
Java
2
star
58

jyp

JSON (planned: + YAML + Property Lists): only 2 classes, no dependencies, simplest API, sane error handling, bean serialization.
Java
2
star
59

BetterUserVoice

UserVoice Admin UI additions
Ruby
2
star
60

hellow

C
2
star
61

mongopool

Provides a concurrency limit and automatic reconnection for mgo
Go
2
star
62

ATExpressiveCollections

More concise, expressive, block-based helpers for Objective-C Foundation collection classes
Objective-C
2
star
63

ATPathSpec

gitignore-style path list matching in Objective-C
Objective-C
2
star
64

seamless-debugger-demo

A proof-of-concept demo of a seamless interpreted script debugger using Eclipse & DLTK
Java
2
star
65

systemproxy

Golang package to get and set systemwide proxy settings
Go
2
star
66

yoursway-magic-ecabu

2
star
67

debugflag

Golang library to enable optional behavior at runtime via DEBUG environment variable
Go
2
star
68

rewebsocket

WebSocket with automatic reconnection
CoffeeScript
2
star
69

naive-language-benchmark

Naïve benchmark of V8, Sun JVM, Ruby, Python and C
Java
2
star
70

sadr-experiment

2
star
71

sem

Limits the concurrency of goroutines
Go
2
star
72

multierr

Merges multiple errors into a single error value in idiomatic Go way
Go
2
star
73

woot

Quickly create new projects based on custom templates
CoffeeScript
2
star
74

yoursway-projectsync

An Eclipse plugin to auto-import projects from disk, and to auto-move projects on disk to proper locations
Java
2
star
75

yoursway-libraries

External libraries in use by various YourSway projects
2
star
76

money-done-right

Python
2
star
77

autoesc.js

Error Short Circuiter (ESC) function decorator
JavaScript
2
star
78

koi-tool

Junk. (A streamline-based throw-away data entry app. Kept for future reference.)
2
star
79

mongobulk

Wraps Golang mgo driver's Bulk type to enables batches of unlimited size
Go
2
star
80

edb

Embedded Database for Go, serializes structs with indices using boltdb (for now; badger version coming)
Go
2
star
81

DeepWorkTimer

Swift
2
star
82

yoursway-taskus

An unfinished project to make a text-based TODO app in SWT. Feel free to reuse under the MIT license. (A legacy of a closed-down company I have owned.)
Java
2
star
83

FSMonitoringKit

Flexible Cocoa file system monitoring library with guaranteed fine-grained change events (based on FSEvents)
Objective-C
2
star
84

sqlexpr

Idiomatic, simple and powerful SQL builder for Go
Go
2
star
85

simple-sharing-service

2
star
86

try_git

1
star
87

binaryio

Buffered Reader and Writer for serializing structured binary data
Go
1
star
88

yoursway-python-commons

Useful Python code (mostly Google App Engine-specific)
Python
1
star
89

primes-refactoring-example

An example code for my lecture on refactoring
1
star
90

PrideAndPrejudiceFanficIndex

Pride & Prejudice Fan Fiction Index — a web app written with Node.js and Twitter Bootstrap (mostly for my own needs, but maybe I will publish it somewhere soon)
JavaScript
1
star
91

twins-js

NodeApp UI controllers library and RPC endpoint
1
star
92

download-papertrail-archives

A Golang script to download all missing archives from Papertrail
Go
1
star
93

ModalMoviePlayerViewController

Display AVPlayerViewController the easy way, with controls initially hidden
Swift
1
star
94

bulk-rename

A bash script to rename/move/copy files by editing file names in your favorite $EDITOR.
Shell
1
star
95

minicomponents

Component support for Go templates (html/template and text/template)
Go
1
star
96

SundaySchool

Sunday school of business, web and app development (in Russian)
1
star
97

mockko

Mockko
CoffeeScript
1
star
98

vkanimal-autoplay

Ruby
1
star
99

easyhttpserver

Production-ready HTTP/HTTPS server in a few lines of Go code
Go
1
star
100

ys-learning-center

JavaScript
1
star