It's not too hard to create a function like this. Just loop through each field in the second object, and if it's not present in the first or the value is different than the first, put that field in the return object.

var compareJSON = function(obj1, obj2) {
  var ret = {};
  for(var i in obj2) {
    if(!obj1.hasOwnProperty(i) || obj2[i] !== obj1[i]) {
      ret[i] = obj2[i];
    }
  }
  return ret;
};

You can see it in action on this demo page.

Answer from Peter Olson on Stack Overflow
🌐
npm
npmjs.com › package › json-diff
json-diff - npm
-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 ... 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
      » npm install json-diff
    
Published   May 15, 2023
Version   1.0.6
Author   Andrey Tarantsov
🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
Discussions

Is there a library that allows to easily do diffchecks between two json?
I mean, you could stringify them both and check if they are equal or not… would be a quick and dirty way. More on reddit.com
🌐 r/reactjs
27
16
October 13, 2022
javascript - Getting a diff of two json-objects - Stack Overflow
Scenario: I want a function that compares two JSON-objects, and returns a JSON-object with a list of the differences and if possible more data such as coverage metrics. var madrid = '{"type&qu... More on stackoverflow.com
🌐 stackoverflow.com
Built a Tool for Deep JSON Comparison - Seeking Input on Array Diff Visualization
jq + diff = totally enough More on reddit.com
🌐 r/golang
6
4
July 30, 2024
Diff two large JSON array or objects
Yes Firstly you have to load json data in python dictionary using json module/package After that jsondiff module/package help you check different This module/package also compare list,set,etc.👌 If will return empty dictionary {} if there is no different👍 import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson) if r : print(r) else: print("404,No Different Found!") Output: {1: 1, 4: 4, delete: [2, 3]} 😀 json.diff take 1st arg oldJson means from which we are checking different & 2nd newJson. There are 3 syntax 🎲 : compact ( default ) Any Change in Value of key & new insrted key will display normaly symmetric Inserted & delete show differently change show normally explicit 👀 It is detailed Inserted Deleted Changed Show differently import jsondiff oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print(r) else: print("404,No Different Found!") Output : {insert: {4: 4}, update: {1: 1}, delete: [2, 3]} 😃 Finally 🔥,Now you doubt about how to access them You can access them using symbols eg. r[jsondiff.symbols.insert] OR from jsondiff import symbols r[symbols.insert] There are some other symbols which use in different compare like list,set, etc Note : if you try using insert in compact & update in compact & symmetric then you will get KeyError 😔 because those not exist there import jsondiff from jsondiff import symbols oldJson = {1:"a",2:"b",3:"c"} newJson = {1:1,4:4} r = jsondiff.diff(oldJson,newJson,syntax="explicit") if r: print("Deleted keys are ",r[symbols.delete]) else: print("404,No Different Found!") Output : Deleted keys are [2, 3] 🥳 Thanks for reading 😂 More on reddit.com
🌐 r/learnpython
3
3
February 26, 2022
People also ask

What is JSDiff?
JSDiff is a free online tool for comparing JSON and JavaScript code. It uses the Myers Difference Algorithm to highlight differences between two text segments, making it easy to see what has been added, removed, or modified.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
Is JSDiff free to use?
Yes, JSDiff is completely free to use. All processing is done locally in your browser, ensuring your data remains private and secure.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
Is my data safe when using JSDiff?
Yes, all data processing happens locally in your browser. No data is sent to any server, ensuring complete privacy and security.
🌐
json.jsdiff.com
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff ...
🌐
GitHub
github.com › benjamine › jsondiffpatch
GitHub - benjamine/jsondiffpatch: Diff & patch JavaScript objects · GitHub
(optionally) text diffing of long strings powered by google-diff-match-patch (diff at character level) reverse a delta, unpatch (eg. revert object to its original state using a delta) ... // sample data const country = { name: 'Argentina', capital: 'Buenos Aires', independence: new Date(1816, 6, 9), }; // clone country, using dateReviver for Date objects const country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver); // make some changes country2.name = 'Republica Argentina'; country2.population = 41324992; delete country2.capital; const delta = jsondiffpatch.diff(country, cou
Starred by 5.3K users
Forked by 496 users
Languages   TypeScript 94.7% | CSS 2.9% | JavaScript 2.4%
🌐
Js
json-diff-kit.js.org
JSON Diff Kit Playground
We cannot provide a description for this page right now
🌐
npm
npmjs.com › package › json-diff-ts
json-diff-ts - npm
1 month ago - Calculate and apply differences between JSON objects with advanced features like key-based array diffing, JSONPath support, and atomic changesets.. Latest version: 4.10.0, last published: 3 days ago.
      » npm install json-diff-ts
    
Published   Mar 06, 2026
Version   4.10.0
Author   Christian Glessner
🌐
DEV Community
dev.to › keploy › diff-json-a-complete-guide-to-comparing-json-data-3e31
Diff JSON – A Complete Guide to Comparing JSON Data - DEV Community
October 15, 2024 - JSON Diff Tools and Libraries ... directly in the terminal. • JSON-diff (npm library): This JavaScript package helps compare JSON objects and outputs differences....
Find elsewhere
🌐
GitHub
github.com › RexSkz › json-diff-kit
GitHub - RexSkz/json-diff-kit: A better JSON differ & viewer, support LCS diff for arrays and recognise some changes as "modification" apart from simple "remove"+"add". · GitHub
You can use your own component to visualize the diff data, or use the built-in viewer: import { Viewer } from 'json-diff-kit'; import type { DiffResult } from 'json-diff-kit'; import 'json-diff-kit/dist/viewer.css'; interface PageProps { diff: [DiffResult[], DiffResult[]]; } const Page: React.FC<PageProps> = props => { return ( <Viewer diff={props.diff} // required indent={4} // default `2` lineNumbers={true} // default `false` highlightInlineDiff={true} // default `false` inlineDiffOptions={{ mode: 'word', // default `"char"`, but `"word"` may be more useful wordSeparator: ' ', // default `""`, but `" "` is more useful for sentences }} /> ); };
Starred by 209 users
Forked by 17 users
Languages   TypeScript 92.7% | Less 4.7% | JavaScript 2.6%
🌐
JSDiff
json.jsdiff.com › home
JSON Diff - The semantic JSON compare tool - JavaScript Text Diff Library | Myers Algorithm Implementation
JSDiff is a free online tool designed specifically for developers. It helps you quickly compare the differences between two segments of JSON or JavaScript code, supporting highlighted display, structured presentation, and one-click merging.
🌐
TechTutorialsX
techtutorialsx.com › 2020 › 03 › 01 › javascript-json-diff
JavaScript: JSON diff – techtutorialsx
January 25, 2025 - In this tutorial we will learn how to use the jsondiffpatch library to detect the difference between two JavaScript objects.
🌐
GitHub
github.com › andreyvit › json-diff
GitHub - andreyvit/json-diff: Structural diff for JSON files · GitHub
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' })); // Out
Starred by 1.2K users
Forked by 138 users
Languages   CoffeeScript 66.6% | JavaScript 33.4%
Top answer
1 of 9
63

It's possible to use a recursive function that iterates by the object keys. Then use the Object.is to test for NaN and null. Then test if the second object is the type that cast to false like 0, NaN, or null. List the keys of both objects and concatenate them to test of missing keys in the obj1 and then iterate it.

When there is a difference between the same key values, it stores the value of object2 and proceeds. If both key values are object means that can be recursively compared and so it does.

function diff(obj1, obj2) {
    const result = {};
    if (Object.is(obj1, obj2)) {
        return undefined;
    }
    if (!obj2 || typeof obj2 !== 'object') {
        return obj2;
    }
    Object.keys(obj1 || {}).concat(Object.keys(obj2 || {})).forEach(key => {
        if(obj2[key] !== obj1[key] && !Object.is(obj1[key], obj2[key])) {
            result[key] = obj2[key];
        }
        if(typeof obj2[key] === 'object' && typeof obj1[key] === 'object') {
            const value = diff(obj1[key], obj2[key]);
            if (value !== undefined) {
                result[key] = value;
            }
        }
    });
    return result;
}

The code above is BSD licensed and can be used anywhere.

Test link: https://jsfiddle.net/gartz/vy9zaof2/54/

An important observation, this will convert arrays to objects and compare the values in the same index position. There are many other ways to compare arrays not covered by this function due to the required extra complexity.

EDIT 2/15/2019: This answer was changed to add the new ES2017 syntax and fix use-cases from comments.


This is just a kickoff, I haven't tested it, but I began with a filter or comparator function, that is recursive, change it however you need to get priority results.

function filter(obj1, obj2) {
    var result = {};
    for(key in obj1) {
        if(obj2[key] != obj1[key]) result[key] = obj2[key];
        if(typeof obj2[key] == 'array' && typeof obj1[key] == 'array') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
        if(typeof obj2[key] == 'object' && typeof obj1[key] == 'object') 
            result[key] = arguments.callee(obj1[key], obj2[key]);
    }
    return result;
}

Tests: http://jsfiddle.net/gartz/Q3BtG/2/

2 of 9
11

contributing back my changes to Gabriel Gartz version. This one works in strict mode and removes the array check - will always be false. It also removes empty nodes from the diff.

//http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object
var isEmptyObject = function(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
};

//http://stackoverflow.com/questions/8431651/getting-a-diff-of-two-json-objects
var diff = function(obj1, obj2) {
    var result = {};
    var change;
    for (var key in obj1) {
        if (typeof obj2[key] == 'object' && typeof obj1[key] == 'object') {
            change = diff(obj1[key], obj2[key]);
            if (isEmptyObject(change) === false) {
                result[key] = change;
            }
        }
        else if (obj2[key] != obj1[key]) {
            result[key] = obj2[key];
        }
    }
    return result;
};
🌐
jQuery Script
jqueryscript.net › jquery plugins › jquery text plugins
Find The Difference Between Two JSON Snippets - JSON Diff | Free jQuery Plugins
January 29, 2019 - A lightweight online JSON diff tool that compares JSON data you provide and highlights the differences between two JSON snippets.
🌐
Playcode
playcode.io › json-diff
JSON Diff Online - Free JSON Compare & Merge Tool
Fast, free, no ads ... PlayCode's JSON diff tool lets you compare and merge JSON files instantly. Unlike other tools cluttered with advertisements, our JSON compare tool is completely free and ad-free.
🌐
GitHub
github.com › viruschidai › diff-json
GitHub - viruschidai/diff-json: A javascript object diff tool
A diff tool for javascript objects inspired by https://github.com/eugeneware/changeset. If a key is specified for an embedded array, the diff will be generated based on the objects have same keys. var changesets = require('diff-json'); var newObj, ...
Starred by 61 users
Forked by 15 users
Languages   CoffeeScript 99.6% | JavaScript 0.4% | CoffeeScript 99.6% | JavaScript 0.4%
🌐
npm
npmjs.com › package › json-diff-kit
json-diff-kit - npm
November 23, 2025 - You can use your own component to visualize the diff data, or use the built-in viewer: import { Viewer } from 'json-diff-kit'; import type { DiffResult } from 'json-diff-kit'; import 'json-diff-kit/dist/viewer.css'; interface PageProps { diff: [DiffResult[], DiffResult[]]; } const Page: React.FC<PageProps> = props => { return ( <Viewer diff={props.diff} // required indent={4} // default `2` lineNumbers={true} // default `false` highlightInlineDiff={true} // default `false` inlineDiffOptions={{ mode: 'word', // default `"char"`, but `"word"` may be more useful wordSeparator: ' ', // default `""`, but `" "` is more useful for sentences }} /> ); };
      » npm install json-diff-kit
    
Published   Mar 03, 2026
Version   1.0.35
Author   Rex Zeng
🌐
JSON Formatter
jsonformatter.org › json-compare
JSON Compare Online to find different between two json
Version Control: When tracking ... added, or removed. JSON Compare refers to the process of comparing two JSON (JavaScript Object Notation) data structures to determine the differences between them....
🌐
DEV Community
dev.to › keploy › json-diff-comparing-and-identifying-changes-in-json-data-2m3m
JSON Diff: Comparing and Identifying Changes in JSON Data - DEV Community
January 14, 2025 - Diffchecker: A versatile online tool for comparing text, JSON, and other data formats. jsondiffpatch (JavaScript): A powerful library for comparing JSON objects and generating diffs programmatically.