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

标签 javascript json node.js

我有两个 json 文件 - data.json 和 dataForUpdate.json

数据.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 和硬编码替换,我该怎么做。

最佳答案

你看过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 - 不支持
  • Edge - 所有版本
  • 歌剧 - 32 岁以上
  • Safari - 9 岁以上

关于javascript - 如何更新 nodejs 中的全部或大部分 JSON 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297604/

相关文章:

java - Jackson - 由于构造函数导致的 JsonMappingException

python - Bottle 框架 : how to return datetime in JSON response

node.js - 导出的 typescript 类函数将 "this"记录为未定义

javascript - 如何在 Node 脚本中使用 React 组件?

javascript - 是否可以确定服务器是否调用了 Meteor 方法

javascript - 重复字符串 - Javascript

python - 连续写入包含数组的JSON文件

javascript - 我如何使用 'gulp-babel' throw ERROR 不要停止 Node 服务器

javascript - 如何将javascript中的字母增加到下一个字母?

javascript - 是否可以从存储在另一个 javascript 文件中的 JSON 对象读取值?