我有一个JSON
响应,其中填充了配置数据,我想用JSON
响应中的各个元素动态填充我的配置变量,而不用写一行来分配每个变量。
检索我的JSON
文件的代码:
configObj = require("./Config.js");
ws_server.getConfigHTTPRequest(function(data){
jsonObject = JSON.parse(data.toString().replace("//","",));
var keys = Object.keys(jsonObject);
keys.forEach(function(key){
//here i want to assign the values to their respective values in the
//config object according to the key value
//i tried this : configObj.key = jsonObject[key], but it doesnt
//assign the values although JSON object keys are named the same
// as my config object variables
console.log(key +': '+ jsonObject[key])
});
});
这是我的配置对象:
module.exports = {
coldfusion_WS : "ws://192.168.#####/cfusion/cfusion/",
readerURI: "tmr://192.168.###",
serialPort: "COM5",
KIOSKID: "3",
kiosktype: "IN",
baudRate: 9600 ,
coldFusionIP:"192.168.###",
coldFusionPort:"81",
JAR_path:"C:/inetpub/wwwroot/KiosksClient/javaapi/",
applicationName:"KioskServerV2",
HTTPPrintUrl:"http://192.168.###/IQNFLOW/kiosk_files/",
PdfFilePath:"C:/inetpub/wwwroot/KiosksClient/print_files/",
PingReaderSleep:"6",
readerPingAddress: "192.168.###" ,
printerName:"USBPRN:Star TUP900 Presenter (TUP992)",
printerThrearSleep:"30000" ,
RFIDThreadSleep:"20" ,
HTTPPath:"/KiosksServer/components/WS.cfc" ,
GOUTIP:"172.16###" ,
GINIP:"172.16.###" ,
paperOut:16 ,
doorOpen:4194304 ,
paperLow:131072 ,
paperNotPulled:2048 ,
readerPower:"20",
driverImagePath:"http://localhost:81/28010948_personal_092957.png" ,
DriverRegWS:"http://localhost:81/driverregistrar/WS/cards.cfc",
driverRegIP:"localhost"
}
答案 0 :(得分:1)
我只需要使用:
configObj[key] = jsonObject[key]
阅读以下文章后获得见识:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
答案 1 :(得分:0)
请注意,如果您只想将传入对象中的每个值复制到配置对象中,则可以不使用循环进行操作:
Object.assign(configObject, jsonObject)
有关更多详细信息,请参见Object.assign。