Skip to content

JSON Diff — Ruby source

Compare two JSON documents structurally: added, removed and changed values reported at exact paths instead of raw text lines. Runs locally in your browser with a shareable link.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# frozen_string_literal: true

# json-diff — structural JSON diff tool. Ruby port (canonical TS:
# src/lib/json-diff.ts; Go twin: cli/json-diff). Mirrors the JS/Python ports:
# both documents are parsed with JSON.parse, then walked in parallel —
# objects over the sorted union of both key sets (key order never matters),
# arrays by shared index with no LCS alignment (a shifted array reports every
# moved index as changed, by design). A type divergence collapses into ONE
# change at the diverging path, never per-child; equality is deep and
# order-insensitive, so same:true means the documents are structurally
# identical. Never raises — errors travel in the result hash: "Left: …" /
# "Right: …" for parse failures, "Both inputs are required" for empty input.
require 'json'

module JsonDiff
  module_function

  # TS deepEqual: Ruby's native == already matches JSON semantics here
  # (1 == 1.0 is true, true == 1 is false, Hash == is deep and
  # order-insensitive).
  def json_equal(a, b)
    a == b
  end

  def walk(left, right, path, out)
    return if json_equal(left, right)

    if left.is_a?(Hash) && right.is_a?(Hash)
      (left.keys | right.keys).sort.each do |key|
        child = "#{path}.#{key}"
        if !left.key?(key)
          out << { 'path' => child, 'type' => 'added', 'after' => right[key] }
        elsif !right.key?(key)
          out << { 'path' => child, 'type' => 'removed', 'before' => left[key] }
        else
          walk(left[key], right[key], child, out)
        end
      end
      return
    end

    if left.is_a?(Array) && right.is_a?(Array)
      shared = [left.length, right.length].min
      (0...shared).each { |i| walk(left[i], right[i], "#{path}[#{i}]", out) }
      (shared...right.length).each do |i|
        out << { 'path' => "#{path}[#{i}]", 'type' => 'added', 'after' => right[i] }
      end
      (shared...left.length).each do |i|
        out << { 'path' => "#{path}[#{i}]", 'type' => 'removed', 'before' => left[i] }
      end
      return
    end

    out << { 'path' => path, 'type' => 'changed', 'before' => left, 'after' => right }
  end

  # Compare two JSON documents structurally. Both inputs are required.
  def json_diff(left_raw, right_raw)
    if left_raw.strip.empty? || right_raw.strip.empty?
      return { 'changes' => [], 'same' => false, 'error' => 'Both inputs are required' }
    end
    begin
      left = JSON.parse(left_raw)
    rescue JSON::ParserError => e
      return { 'changes' => [], 'same' => false, 'error' => "Left: #{e.message}" }
    end
    begin
      right = JSON.parse(right_raw)
    rescue JSON::ParserError => e
      return { 'changes' => [], 'same' => false, 'error' => "Right: #{e.message}" }
    end
    changes = []
    walk(left, right, '$', changes)
    { 'changes' => changes, 'same' => changes.empty?, 'error' => nil }
  end
end

# Example:
# JsonDiff.json_diff('{"name": "ada"}', '{"name": "grace"}')['changes']
# → [{ 'path' => '$.name', 'type' => 'changed', 'before' => 'ada', 'after' => 'grace' }]
# JsonDiff.json_diff('[1, 2]', '[1, 2, 3]')['changes']
# → [{ 'path' => '$[2]', 'type' => 'added', 'after' => 3 }]

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →