我将如何更改 json 文件中字符串中的值?

How i will change the value in the string in json file?

我正在尝试更改 JSON 文件中字符串的值,但它无法正常工作。

示例 JSON 文件:

{'user1':{"name":"example","age":32,"coins":16}}

我试过用这个:

let fs = require('fs')
let file = fs.readFileSync('./example.json','utf-8')
file.user1.name = "example example"
fs.writeFileSync('./example.json',JSON.stringify(file,null,1))

它不会 return 任何错误,但它会使 JSON 文件如下所示:

{'user1':{'name':'example','age':32,'coins':16}},
  "name": "example example"
 }
}

和这个 JSON 文件更新了 discord 中的每条消息 (是的,这是给 discord 机器人的 ^_^)

您应该使用 require 加载 json 模块,因为它会自动解析 JSON:

const fs = require('fs')
const file = require('./example.json');
file.user1.name = "example example";
fs.writeFileSync('./example.json',JSON.stringify(file,null,1))