Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何更改json文件中字符串中的值?_Node.js_Fs - Fatal编程技术网

Node.js 如何更改json文件中字符串中的值?

Node.js 如何更改json文件中字符串中的值?,node.js,fs,Node.js,Fs,我正在尝试更改JSON文件中字符串的值,但它的工作方式与我需要的不一样 JSON文件示例: {'user1':{"name":"example","age":32,"coins":16}} 我试着用这个: let fs = require('fs') let file = fs.readFileSync('./example.json','utf-8') file.user1.name = "exampl

我正在尝试更改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))
它不会返回任何错误,但会将JSON文件保留如下内容:

{'user1':{'name':'example','age':32,'coins':16}},
  "name": "example example"
 }
}
这个JSON文件会更新discord中的每条消息
(是的,这适用于discord bot^^)

您应该使用
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))