2

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?

1 Answer 1

2
    //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"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.