JS debug: visually compare two objects or JSONs in browser

Today I was trying to find differences between two objects (coming from JSON API) during debugging in Chrome. First, I was printing them separately using console.log() and then copy-pasting into http://www.jsondiff.com/ for visual inspection. When I did it 3 times I decided I need better approach. So I wrote helper static function (ES6 syntax):

class Utils { 
  static logComparison(message, a, b) { 
    const encodedJsonA = encodeURIComponent(JSON.stringify(a)) 
    const encodedJsonB = encodeURIComponent(JSON.stringify(b)) 
    const link = `http://www.jsondiff.com/?left=${encodedJsonA}&right=${encodedJsonB}` 
    console.log(message, link) 

Utils.logComparison( "Test", {a: 5, c: [1, 2, 3], b: 7}, {a: 5, b: 42, c: [1, 3]} )

How does it work?

  1. It converts JS objects into JSON string
  2. Encode that string so it can be used in URL
  3. Compose URL to jsondiff.com with both serialized objects as parameters
  4. Print this link into console together with message - so you can have some debugging context.

When executed, it prints following into Chrome/Firefox/MaybeOther Developer Tools console:


If you click on that link, it opens new tab with visual comparison:


Please note that jsondiff.com can even handle scattered keys and missing array entries. It is so cool and does not need to install any special plugins. Handy little trick, don’t you think so?

Tags:  Debug  JavaScript