Skip to content

json diff

this is json diff example

2 min read

astro tabs components

function

function compareAndMarkJSON(obj1, obj2) {
  const result = {};

  // 获取所有键,包括 obj1 和 obj2 的键
  const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);

  keys.forEach(key => {
    // 如果 obj1 中没有该键,说明是新增的字段
    if (!(key in obj1)) {
      result[key] = { value: obj2[key], __status: "added" };
    }
    // 如果 obj2 中没有该键,说明是删除的字段
    else if (!(key in obj2)) {
      result[key] = { value: obj1[key], __status: "removed" };
    }
    // 如果两个对象中都有该键,进一步比较值
    else {
      const value1 = obj1[key];
      const value2 = obj2[key];

      // 如果值是对象,递归比较
      if (
        typeof value1 === "object" &&
        typeof value2 === "object" &&
        value1 !== null &&
        value2 !== null
      ) {
        result[key] = compareAndMarkJSON(value1, value2);
      }
      // 如果值不相等,说明是修改的字段
      else if (value1 !== value2) {
        result[key] = { value: value2, __status: "modified", oldValue: value1 };
      }
      // 如果值相等,说明未修改
      else {
        result[key] = { value: value1, __status: "unchanged" };
      }
    }
  });

  return result;
}

example

// 示例用法
const json1 = {
  name: "Alice",
  age: 25,
  address: {
    city: "Wonderland",
    zip: "12345",
  },
  hobbies: ["reading", "traveling"],
};

const json2 = {
  name: "Alice",
  age: 30,
  address: {
    city: "Wonderland",
    zip: "67890",
  },
  hobbies: ["reading", "traveling"],
  newField: "This is new",
};

const markedJSON = compareAndMarkJSON(json1, json2);
console.log(JSON.stringify(markedJSON, null, 2));
{
  "name": {
    "__status": "unchanged",
    "value": "Alice"
  },
  "age": {
    "__status": "modified",
    "oldValue": 25,
    "newValue": 30
  },
  "address": {
    "city": {
      "__status": "unchanged",
      "value": "Wonderland"
    },
    "zip": {
      "__status": "modified",
      "oldValue": "12345",
      "newValue": "67890"
    }
  },
  "hobbies": {
    "__status": "unchanged",
    "value": ["reading", "traveling"]
  },
  "newField": {
    "__status": "added",
    "value": "This is new"
  }
}

Last modify by: Apr 16, 2026