Ad

How To Store Array Of Objects In Db.json From Json-server

- 1 answer

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?

Ad

Answer

Modifying the AJAX call to send stringify object and setting the contentType: "application/json" did the trick

Modified the AJAX call as below-

$.ajax({
      type: "POST",
      url: this.serverUrl,
      data: JSON.stringify(val),
      contentType: "application/json"
 });
Ad
source: stackoverflow.com
Ad