I am creating a fake backend using json-server to store some data in json format. The data is complex as follows -
{
"id": 0,
"quizName": "Which Harry Potter Character Are You?",
"characters": ["Harry", "Ron", "Hermoine"],
"qa": [{
"question": "Do you play Chess?",
"answers": [{
"name": "yes",
"charscore": [0, 1, 0]
},
{
"name": "no",
"charscore": [1, 0, 1]
}
]
},
{
"question": "Do you spell magic correctly?",
"answers": [{
"name": "yes",
"charscore": [0, 0, 1]
},
{
"name": "no",
"charscore": [1, 1, 0]
}
]
},
{
"question": "Do you have a Scar?",
"answers": [{
"name": "yes",
"charscore": [1, 0, 0]
},
{
"name": "no",
"charscore": [0, 1, 1]
}
]
}
]
}
But when I do jQuery POST to the json-server, the json data is stored as follows -
{
"quizName": "Which Harry Potter Character Are You?",
"characters[]": [
"Harry",
"Ron",
"Hermoine"
],
"qa[0][question]": "Do you play Chess?",
"qa[0][answers][0][name]": "yes",
"qa[0][answers][0][charscore][]": [
"0",
"1",
"0"
],
"qa[0][answers][1][name]": "no",
"qa[0][answers][1][charscore][]": [
"1",
"0",
"1"
],
"qa[1][question]": "Do you spell magic correctly?",
"qa[1][answers][0][name]": "yes",
"qa[1][answers][0][charscore][]": [
"0",
"0",
"1"
],
"qa[1][answers][1][name]": "no",
"qa[1][answers][1][charscore][]": [
"1",
"1",
"0"
],
"qa[2][question]": "Do you have a Scar?",
"qa[2][answers][0][name]": "yes",
"qa[2][answers][0][charscore][]": [
"1",
"0",
"0"
],
"qa[2][answers][1][name]": "no",
"qa[2][answers][1][charscore][]": [
"0",
"1",
"1"
],
"id": 1
}
The post method is as follows-
$.post(this.serverUrl, val, function (serverResponse) {
//val contains the expected javascript object
console.log(serverResponse);
});
How can I store the values correctly in json-server?
JSON.stringify(serverResponse)to save JSON object properly or either use this url (scotch.io/tutorials/…) to get some help to how to store data in JSON-Server{ "{\"quizName\":\"Which Harry Potter Character Are You?\",\"characters\":[\"harry\",\"ron\",\"harmione\"],\"qa\":[{\"question\":\"do u play chess?\",\"answers\":[{\"name\":\"yes\",\"charscore\":[0,1,0]},{\"name\":\"no\",\"charscore\":[1,0,1]}]},{\"question\":\"do u have scar?\",\"answers\":[{\"name\":\"yes\",\"charscore\":[1,0,0]},{\"name\":\"no\",\"charscore\":[0,1,1]}]},{\"question\":\"du u spell magic?\",\"answers\":[{\"name\":\"yes\",\"charscore\":[0,0,1]},{\"name\":\"no\",\"charscore\":[1,1,0]}]}]}": "", "id": 1 }stringifyand when you want to use it back as JSON object you can useJSON.parse(serverResponse)