1

I am fairly new to Javascript and nodejs. I would like a JSON file (results.json) that takes the format of something similar to this:

Starts off as:

{
  "name":"John",
  "task":[]
}

then eventually becomes something like this with nested arrays:

{
  "name":"John",
  "task":[ ["task1","task2"], ["task3", "task4"] ]
}

I want to push to the "task" array a new list of tasks (always of size 2) everytime something is done (in my case when a form is submitted with a button-press).

So for example, after another "action", the JSON file will look something like this:

{
  "name":"John",
  "task":[ ["task1","task2"], ["task3", "task4"] , ["task5", "task6"] ]
}

NOTE: "task(1,2,...,6) was just used as an example, these will be other strings corresponding to the form submission.

This is what I have so far in my server-side file:

var fs = require('fs')

app.post("/addtask", function(req, res) {
fs.readFile('results.json', function (err, data) {
    var json = JSON.parse(data)
    var newTask1 = req.body.newtask1
    var newTask2 = req.body.newtask2

    //WHAT DO I PUT HERE

    fs.writeFile("results.json", JSON.stringify(json))
})
});

Please do correct me if my syntax is wrong or if my idea of how a JSON file works is wrong.

1 Answer 1

2

Just push the data as an array

var resObj= {
  "name":"John",
  "task":[]
}

var newTask1 = "task1";
var newTask2 = "task2";

resObj.task.push([newTask1,newTask2]);

console.log(resObj);

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.