Dr.G
Dr.G

Reputation: 493

Stringify in objects JSON inside a object JSON

This is my object JSON:

var myJSon = {
    "Student": "name",
    "Answers":{ 
        "Answer1": {
            "question": "question",
            "answer": "black",
            "time": "00:02:30",
            "number_tentatives": "1"
        },
        "Answer2": {
            "question": "question",
            "answer": "black",
            "time": "00:02:30",
            "number_tentatives": "2"
        }
    }
};

I need to fill in the object "Answer1" or "Answer2". I tried

myJSon.Respostas = JSON.stringify("One","hello","00:03:22","1");

But this results in {Student":"\"name\"","Answers":"\"oi\"}

What I would like is {"Student": "\"name\"", "Answers": {"Answer1": {"question": "One", "answer": "hello" ,"time":"00:03:22" ,"number_tentatives": "1"}, "

Upvotes: 2

Views: 3777

Answers (2)

tiborK
tiborK

Reputation: 385

If you want to add additional data, then you could try this:

myJSon.Answers.Answer3 ={"question":"One","answer":"hello","time":"00:03:22","number_tentatives":"1"};

then test it like

console.log(JSON.stringify(myJSon));

Upvotes: 1

Alex Szabo
Alex Szabo

Reputation: 3276

If you have an object containing multiple answers, it should be an array or map of answers.

Let's think of your object's initial state as this:

var myJson = {student: 'Student Name', answers: []};

So then you could start filling the answers array like:

myJson.answers.push({question: 'q', answer: 'a', time: 1, number_tentatives: 1});

If you'd now access myJson.answers it would be an array with one answer in it.

If you still think the way to go would be objects (so a 'key' is assigned to each answer), you would do this, instead of push:

myJson.answers['answer1'] = {question: 'q', answer: 'a', time: 1, number_tentatives: 1};

Upvotes: 2

Related Questions