最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I update a key value of JSON file? - Stack Overflow

programmeradmin5浏览0评论

I have below JSON in which I want to update Test1 object values. My requirement is that after 1 hour, I have to generate new token and update access_token, time_updated and time_created in Test1 object. Rest things must be same. I don't want to change anything except Test1 object.

Please help me. It would be a great favour for me.

Thank you

{
   "Test1":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    },

     "Test2":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    }
}

I have below JSON in which I want to update Test1 object values. My requirement is that after 1 hour, I have to generate new token and update access_token, time_updated and time_created in Test1 object. Rest things must be same. I don't want to change anything except Test1 object.

Please help me. It would be a great favour for me.

Thank you

{
   "Test1":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    },

     "Test2":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    }
}
Share Improve this question edited Jul 29, 2021 at 6:57 Taslim Arif asked Jul 29, 2021 at 3:23 Taslim ArifTaslim Arif 371 gold badge1 silver badge5 bronze badges 5
  • One interesting issue with node js fs module which I found is when I am trying to read json file from the same directory( fs.readFileSync('./filename.json')) where my code logic file is, it works fine, JSON.parse() gives me JS object and I can access keys but when JSON file is outside directory of my code logic file( say fs.readFileSync('../filename.json') ), JSON.parse() returns string. Is it problem with fs or I am facing this. I am using Typescript. – Taslim Arif Commented Jul 29, 2021 at 6:47
  • I don't think fs has anything to do with it, it sounds more like your other JSON file's contents were stringified twice. This is just guesswork though, you would have to show us the code and the exact contents of the JSON file to troubleshoot it. Also you didn't mention what string you get. – CherryDT Commented Jul 29, 2021 at 7:01
  • So, is this a backend process that is only using Node.js? Or are you using this in a browser? This matters as there are Web APIs available in the browser that are not available in Node.js. See: stackoverflow./questions/38367036/… – Steve Commented Jul 29, 2021 at 15:06
  • I used require() to import JSON and it worked but it has it's own downside. @CherryDT, my exact JSON contains critical credentials which I can't share publicly. I don't think, you understood my requirements properly. I am asking to update a particular key of JSON not writing in whole file again. Because if I do so wherever I am going to use this code( say I build a npm package of it and installed in some other project), it will create JSON file there as well as soon as I call this functionality which I don't want. – Taslim Arif Commented Aug 1, 2021 at 0:53
  • Sorry I don't understand what you just wrote. Aren't those two the same thing? To update a single key you have to read the whole file, update the key in memory and write the whole file back. About the credentials, you could just replace the secrets with dummy text (only the actual values, not any keys or part of the syntax), I'm more interested in the structure. And in regards to your last point it makes no sense to me either - if you would call it in a project without the file it would crash, not create anything, but then I don't know why you'd even call it there if there is no data to change – CherryDT Commented Aug 1, 2021 at 9:03
Add a ment  | 

3 Answers 3

Reset to default 2

Try this

var  data = {
   "Test1":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    },

     "Test2":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    }
};

Object.entries(data).forEach(([key, value]) => {
    if(key === "Test1"){     
     data[key].time_created = "NewValue";
     }
});

console.log(data);

As JSON is technically a string, I am assuming that you are wanting to take a JSON string and change the data inside it, all while keeping is as a string.

First you would need to convert it to a JavaScript Object. Once it is an Object, then you can just use dot notation into the object to change the values that you want.

Lastly, you would convert that JavaScript Object back into a JSON string.

Of course, if you are referring to a JavaScript Object and not a JSON string, then you would just need to use the dot notation to change the values.

See snippet below.

let jsonString = `{
   "Test1":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    },

     "Test2":{
        "type" : "type",
        "client_id": "xyz",
        "client_secret": "xyz",
        "grant_type": "av",
        "token_uri": "url",
        "resource":"resource",
        "access_token" : "",
        "time_created":2342524,
        "time_updated":1612251593
    }
}`;



function updateJson() {

  //Convert the JSON string to a JavaScript Object
  const jsObject = JSON.parse(jsonString);

  //Set the value using dot notation.
  //I just set some random values for the example
  //You would insert your values here: 
  jsObject.Test1.access_token = btoa((Math.random() * 100) ** 10);
  jsObject.Test1.time_created = Math.random() * 100;
  jsObject.Test1.time_updated = Date.parse(new Date()) / 1000;

  //Convert the JavaScript Object back into a JSON string
  jsonString = JSON.stringify(jsObject, null, 2);

  console.log(jsonString)
}
button {
  padding: 10px;
  color: black;
  background: white;
  border-radius: 5px;
}
<button type="button" onclick="updateJson()">Click to Update</button>

Here is the code that might guide you to your purpose. Firstly, you have to be familiar with JSON data such as how to access/modify an element in JSON. The first parts of the code below introduce some general idea of accessing and modifying JSON.

The second part is about how to trigger a function every x sec with the setTimeout() function.

let mydata= {
  "Test1":{
       "type" : "type",
       "client_id": "xyz",
       "client_secret": "xyz",
       "grant_type": "av",
       "token_uri": "url",
       "resource":"resource",
       "access_token" : "",
       "time_created":2342524,
       "time_updated":1612251593
   },

    "Test2":{
       "type" : "type",
       "client_id": "xyz",
       "client_secret": "xyz",
       "grant_type": "av",
       "token_uri": "url",
       "resource":"resource",
       "access_token" : "",
       "time_created":2342524,
       "time_updated":1612251593
   }
}

//This part shows how to access to JSON data
console.log(mydata.Test1.time_created);
console.log(mydata.Test1.time_updated);

mydata.Test1.time_created = 01;
mydata.Test1.time_updated = 02;

console.log(mydata.Test1.time_created);
console.log(mydata.Test1.time_updated);

console.log(typeof mydata.Test1.time_created);
console.log(typeof mydata.Test1.time_updated);

console.log(mydata.Test1);


//This part shows how to trigger doAThingEveryHour 
function doAThingEveryHour() {
  setTimeout(doAThingEveryHour,5*1000)//Trigger doAThingEveryHour  every 5s
  mydata.Test1.time_updated = Date.now();
  console.log("timeUpdate:" + mydata.Test1.time_updated);
}
setTimeout(doAThingEveryHour,5*1000)

发布评论

评论列表(0)

  1. 暂无评论