我有两个json文件 - data.json和dataForUpdate.json
data.json:
[{"name": "test",
"isDefault": true,
"settings": {
"type": "Separation",
"scanner": {
"brightness": 0,
"contrast": 0,
"threshold": 0,
"isDuplex": false,
},
"image": {
"invertImage": false,
"autoRotate": true,
"rotateValue": -180
}
}
}]
dataForUpdate.json:
[{"name": "other",
"isDefault": false,
"settings": {
"scanner": {
"brightness": 100,
"contrast": 50,
},
"image": {
"autoRotate": false,
"rotateValue": 0
}
}
}]
我需要使用第二个值更新第一个json。如果没有JSON.parse和hardcodded替换,我怎么能这样做。
答案 0 :(得分:2)
你看过Object.assign了吗?你可以这样做:
var data = [{"name": "test",
"isDefault": true,
"settings": {
"type": "Separation",
"scanner": {
"brightness": 0,
"contrast": 0,
"threshold": 0,
"isDuplex": false,
},
"image": {
"invertImage": false,
"autoRotate": true,
"rotateValue": -180
}
}
}]
var dataForUpdate = [{"name": "other",
"isDefault": false,
"settings": {
"scanner": {
"brightness": 100,
"contrast": 50,
},
"image": {
"autoRotate": false,
"rotateValue": 0
}
}
}]
Object.assign(data[0], dataForUpdate[0]);
浏览器兼容性
答案 1 :(得分:1)
不使用任何方法,您可以迭代json并更新匹配键并以递归方式调用对象。
var data = {"name": "test",
"isDefault": true,
"settings": {
"type": "Separation",
"scanner": {
"brightness": 0,
"contrast": 0,
"threshold": 0,
"isDuplex": false,
},
"image": {
"invertImage": false,
"autoRotate": true,
"rotateValue": -180
}
}
}
var dataForUpdate = {"name": "other",
"isDefault": false,
"settings": {
"scanner": {
"brightness": 100,
"contrast": 50,
},
"image": {
"autoRotate": false,
"rotateValue": 0
}
}
}
var update = function(a, b) {
for(key in a) {
if(b[key] !== undefined) {
if(typeof b[key] === 'object') {
update(a[key],b[key]);
} else {
a[key] = b[key];
}
}
}
}
update(data, dataForUpdate);
console.log(data);
答案 2 :(得分:0)
如果您使用的是jQuery,那么您也可以使用jQuery extend。
喜欢这个
var data = [{"name": "test",
"isDefault": true,
"settings": {
"type": "Separation",
"scanner": {
"brightness": 0,
"contrast": 0,
"threshold": 0,
"isDuplex": false,
},
"image": {
"invertImage": false,
"autoRotate": true,
"rotateValue": -180
}
}
}];
var update = [{"name": "other",
"isDefault": false,
"settings": {
"scanner": {
"brightness": 100,
"contrast": 50,
},
"image": {
"autoRotate": false,
"rotateValue": 0
}
}
}];
$.extend(data[0],update[0]);
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>