简体   繁体   English

使用 Javascript 更新 json 文件中的 json 密钥?

[英]Update a json key inside a json file using Javascript?

I have a JSON file, I need to read that JSON file and update a particular key with new values.我有一个 JSON 文件,我需要阅读该 JSON 文件并使用新值更新特定键。 How can I do it with the help of javascript in the typescript file?如何在 typescript 文件中的 javascript 的帮助下做到这一点?

datafile.json:数据文件.json:

{
   "Id": {
       "place": {
           "operations": [{
               "Name": "John",
               "Address": "USA"
           }]
       }
   }
}

Now in my test.ts file现在在我的 test.ts 文件中

const filepath = 'c:/datafile.json';
var testjson = filepath.Id[place][operations][0];
var mykey = 'Address';

//testjson[mykey] = 'UK';

updateJsonFile(filepath, (data) => {
  data[mykey] = 'UK';
  console.log(data);
  return data;
});

The issue is it update the JSON with new key and values as below:问题是它使用新的键和值更新 JSON,如下所示:

{
    "Id": {
        "place": {
            "operations": [{
                "Name": "John",
                "Address": "USA"
            }]
        }
        "Address": "UK"
    }
}

But I want to just change the value of a particular key then adding new keys.但我只想更改特定键的值,然后添加新键。 Is it possible in JS.?在JS中可以吗?

data doesn't have an Address property, its operations , which is inside place . data没有Address属性,它的operations位于place内部。

If you try to set it like如果您尝试将其设置为

data[mykey] = 'UK';

it will create a new property to data ,它将为data创建一个新属性,

It should be它应该是

o.Id.place.operations[0][mykey] = 'UK';

 jsonString = ` { "Id": { "place": { "operations": [{ "Name": "John", "Address": "USA" }] } } } `; let o = JSON.parse(jsonString); var mykey = 'Address'; o.Id.place.operations[0][mykey] = 'UK'; console.dir(o);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM