如何更新nodejs中的全部或大部分JSON值?

我有两个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和hardcoddedreplace。

如果不使用任何方法,您可以遍历JSON并更新匹配键并recursion调用对象。

 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); 

你看过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]); 

浏览器兼容性

  • Chrome – 45 +
  • Firefox – 34+
  • Internet Explorer – 不支持
  • 边缘 – 所有版本
  • 歌剧 – 32+
  • Safari – 9+

如果你使用的是jQuery,那么你也可以使用jQuery的扩展 。

喜欢这个

 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>