-1

I have a JSON file, I need to read that JSON file and update a particular key with new values. How can I do it with the help of javascript in the typescript file?

datafile.json:

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

Now in my test.ts file

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:

{
    "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.?

B45i
  • 2,368
  • 2
  • 23
  • 33
Mia
  • 448
  • 8
  • 22
  • Are you sure that its the actual JSON generated by your code?. That JSON is invalid, It is missing a ',' before '"Address": "UK"' value, This won't happen if it was generated by the code. – B45i Jun 04 '20 at 20:04
  • You can't take a path to a file (which is a string), and magically get data from it. You have to load it, either using `require(filepath)` or loading the file and using `JSON.parse()`. – Heretic Monkey Jun 04 '20 at 20:25
  • Does this answer your question? [Using Node.JS, how do I read a JSON file into (server) memory?](https://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-file-into-server-memory) – Heretic Monkey Jun 04 '20 at 20:26
  • You have other problems in your code, but those don't matter until you get the data and parse it into memory. – Heretic Monkey Jun 04 '20 at 20:26

1 Answers1

2

data doesn't have an Address property, its operations, which is inside place.

If you try to set it like

data[mykey] = 'UK';

it will create a new property to 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);
B45i
  • 2,368
  • 2
  • 23
  • 33
  • HI, I asked how to edit the JSON file not console.log. I just wanted to know how to update the json file. btw what does console.dir does? – Mia Jun 05 '20 at 04:25
  • StackOverFlow runs in the browser, it's not possible to do file operations, and its the demo, the actual answer is, Use"o.Id.place.operations[0][mykey] = 'UK';" instead of "data[mykey] = 'UK';". Provided code for accessing JSON works. You can google what console.dir does. – B45i Jun 05 '20 at 13:14