How do I use this json module properly?

时间:2018-03-23 00:39:56

标签: javascript

Could someone please explain how do I properly use this JS module https://github.com/Cocycles/electron-storage

Created json file:

{
  "test": []
}

Question:

I've created the file by calling storage.set(filePath, {"test": []}) but how do I change the properties now?

For example, how would I add string "path1" into the "test" property of that json file?

When I do the following, it just replaces everything in the file:

storage.get(filePath)
.then(data => { storage.set(filePath, data["test"] = "path1") }

1 个答案:

答案 0 :(得分:1)

you'll have to get the variable, update it and then put it back again, try this :

storage.get(filePath)
    .then(data => {
        data.test.push("path1"); // this will add "path1" to your array and not overwrite it
        storage.set(filePath, data)
    })
    .catch(err => {
      console.error(err);
    });

according to your edit : what you needed is to add "path1" to the array test with push