JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,常用于將數據從服務器傳遞到客戶端。當我們處理JSON數據時,經常需要比對兩個JSON串的內容,以檢查它們是否相同或者有哪些差異。下面我們將介紹如何比對兩個JSON串內容。
//第一個JSON串 { "name": "Amy", "age": 25, "sex": "female", "adress": { "city": "Beijing", "province": "Bejing", "country": "China" }, "hobby": ["reading", "singing", "travel"], "education": [ { "degree": "bachelor", "school": "Tsinghua University" }, { "degree": "master", "school": "Peking University" } ] }
//第二個JSON串 { "name": "Amy", "age": 25, "sex": "female", "adress": { "city": "Beijing", "province": "Bejing", "country": "China" }, "hobby": ["reading", "singing", "swimming"], "education": [ { "degree": "bachelor", "school": "Tsinghua University" }, { "degree": "master", "school": "Harvard University" } ] }
首先,我們可以解析這兩個JSON串并轉換為JavaScript對象,然后使用for-in循環遍歷檢查每一個鍵值對。具體代碼如下:
const obj1 = JSON.parse(json1); const obj2 = JSON.parse(json2); function compareJSON(obj1, obj2) { for (let key in obj1) { if (typeof obj1[key] !== typeof obj2[key]) { return false; } if (typeof obj1[key] === 'object') { if (!compareJSON(obj1[key], obj2[key])) { return false; } } else if (obj1[key] !== obj2[key]) { return false; } } for (let key in obj2) { if (!obj1.hasOwnProperty(key)) { return false; } } return true; } console.log(compareJSON(obj1, obj2));
代碼中使用遞歸的方式來遍歷兩個JSON對象。如果兩個JSON對象不是同一類型,或者值不相等,或者鍵名不一致就返回false,否則就返回true。
比較結果為false,因為兩個JSON對象中,Amy的第二個愛好不同,她的第二個學位學校也不同。
上一篇用css3做游戲
下一篇2d骨骼動畫 json