JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,常用于將數(shù)據(jù)從服務(wù)器傳遞到客戶端。當(dāng)我們處理JSON數(shù)據(jù)時(shí),經(jīng)常需要比對(duì)兩個(gè)JSON串的內(nèi)容,以檢查它們是否相同或者有哪些差異。下面我們將介紹如何比對(duì)兩個(gè)JSON串內(nèi)容。
//第一個(gè)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" } ] }
//第二個(gè)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" } ] }
首先,我們可以解析這兩個(gè)JSON串并轉(zhuǎn)換為JavaScript對(duì)象,然后使用for-in循環(huán)遍歷檢查每一個(gè)鍵值對(duì)。具體代碼如下:
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));
代碼中使用遞歸的方式來遍歷兩個(gè)JSON對(duì)象。如果兩個(gè)JSON對(duì)象不是同一類型,或者值不相等,或者鍵名不一致就返回false,否則就返回true。
比較結(jié)果為false,因?yàn)閮蓚€(gè)JSON對(duì)象中,Amy的第二個(gè)愛好不同,她的第二個(gè)學(xué)位學(xué)校也不同。