gpt4 book ai didi

javascript - 使用功能文件更新 JSON 元素

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:25 25 4
gpt4 key购买 nike

我想更新 JSON 文件中某个属性的值。如果我在代码中传递属性名称,我就可以更新它。但是,如果我尝试在功能文件中传递该属性名称,则会在 JSON 文件中创建附加元素。

工作代码:

await (function replaceJSONData(callback) {
fs.readFile(requestPath, 'utf8', function (err, data) {
var tempJSON = JSON.parse(data);
tempJSON. = customer.personalDetails.customerFullName = "Amanda"
console.log(tempJSON);
});
});

失败并在 JSON 请求中创建新 Node 元素:

//NOTE: nodeValue_1 is argument coming from feature file which has value as
|nodeValue_1 |
|customer.personalDetails.customerFullName|

this.Given(/^I replace (.*) and (.*) for rest service (.*) from (.*)$/, function (nodeValue_1, nodeValue_2, rest_url, filePath, callback) {
var requestPath = requestDataPath+'\\'+rest_url+'-req.json';
var currentAccount = fs.readFileSync(runTimeDataPath+'\\'+filePath, 'utf8');
console.log(nodeValue_1);
await (function replaceJSONData(callback) {
fs.readFile(requestPath, 'utf8', function (err, data) {
var tempJSON = JSON.parse(data);
//This will add new element called as nodeValue_1 in JSON - FAILS
tempJSON.nodeValue_1 = "Amanda";
console.log(tempJSON);
});
});
});

JSON 更新请求:

{
"customer": {
"personalDetails": {
"userTitle": "Mr",
"customerFullName": "MrSchaumann",
"dateOfBirth": "1980-05-08",
"customerSureName": "Baganz"
}
}
}

最佳答案

这里 tempJSON.nodeValue_1 不起作用,因为 nodeValue_1 是一个变量。尝试使用

tempJSON[nodeValue_1]

nodeValue_1 不会解析为点表示法的值,但如果您使用 tempJSON[nodeValue_1],它将得到解析。

所以你的最终代码应如下所示:

//NOTE: nodeValue_1 is argument coming from feature file which has value as
|nodeValue_1 |
|customer.personalDetails.customerFullName|

this.Given(/^I replace (.*) and (.*) for rest service (.*) from (.*)$/,
function (nodeValue_1, nodeValue_2, rest_url, filePath, callback) {
var requestPath = requestDataPath+'\\'+rest_url+'-req.json';
var currentAccount = fs.readFileSync(runTimeDataPath+'\\'+filePath, 'utf8');
console.log(nodeValue_1);
await (function replaceJSONData(callback) {
fs.readFile(requestPath, 'utf8', function (err, data) {
var tempJSON = JSON.parse(data);
//This will update the value as you expect.
tempJSON[nodeValue_1] = "Amanda";
console.log(tempJSON);
});
});
});

关于javascript - 使用功能文件更新 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49535687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com