使用NodeJS将新行写入JSON文件

时间:2019-02-16 21:03:37

标签: node.js json express

我有一个JSON文件,我想使用NodeJS在此JSON文件中添加一个条目。

已经到处寻找答案,但是我没有找到适合我的具体情况的答案。

我的 pages.json 看起来像这样:

{
"/login":"Login",
"/register":"Register",
"/impressum":"Impressum",
"/createarticle":"Create Article",
"/articles":"Articles",
"/editarticle":"Edit Article",
"/viewarticle":"View Article",
"/viewaccount":"View Account",
"/acp":"Admin Control Panel",
"/usersearch":"User Search",
"/edituser":"Edit User",
"/404":"404 Error",
"/":"Home"
}

然后使用NodeJS,我想向JSON添加一行新内容。

我要在JSON文件中的最后一对之后紧接一行,例如“ / test”:“测试站点” 。 该文件应如下所示:

{
"/login":"Login",
"/register":"Register",
"/impressum":"Impressum",
"/createarticle":"Create Article",
"/articles":"Articles",
"/editarticle":"Edit Article",
"/viewarticle":"View Article",
"/viewaccount":"View Account",
"/acp":"Admin Control Panel",
"/usersearch":"User Search",
"/edituser":"Edit User",
"/404":"404 Error",
"/":"Home",
"/test":"Test Site"
}

如何使用NodeJS和Express做到这一点?

1 个答案:

答案 0 :(得分:0)

    //store your JSON into a string; could be read from a .json file too:
let json = `{
    "/login":"Login",
    "/register":"Register",
    "/impressum":"Impressum",
    "/createarticle":"Create Article",
    "/articles":"Articles",
    "/editarticle":"Edit Article",
    "/viewarticle":"View Article",
    "/viewaccount":"View Account",
    "/acp":"Admin Control Panel",
    "/usersearch":"User Search",
    "/edituser":"Edit User",
    "/404":"404 Error",
    "/":"Home"
}`;

//convert JSON string to JS object:
let obj = JSON.parse(json); //use try / catch block, omitted here

obj["/test"] ="Test Site";

console.log(JSON.stringify(obj, undefined, 2));

这是控制台输出,请看最后一个属性:

{
  "/login": "Login",
  "/register": "Register",
  "/impressum": "Impressum",
  "/createarticle": "Create Article",
  "/articles": "Articles",
  "/editarticle": "Edit Article",
  "/viewarticle": "View Article",
  "/viewaccount": "View Account",
  "/acp": "Admin Control Panel",
  "/usersearch": "User Search",
  "/edituser": "Edit User",
  "/404": "404 Error",
  "/": "Home",
  "/test": "Test Site"
}