LeonMrBonnie
LeonMrBonnie

Reputation: 90

Writing a new line to JSON file using NodeJS

I have a JSON file, and I want to add a single entry to this JSON file using NodeJS.

Already looked around for an answer, but I didn't find one for my specific case.

My pages.json looks like this:

{
"/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"
}

And using NodeJS I want to add a single new line to the JSON.

I want a line for example "/test":"Test Site" directly after the last pair in the JSON file. The file should then look like this:

{
"/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"
}

How can I do this using NodeJS and Express?

Upvotes: 2

Views: 1742

Answers (1)

arnold
arnold

Reputation: 775

    //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));

And here's the console output, look at the very last property:

{
  "/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"
}

Upvotes: 2

Related Questions