Runicode Runicode - 2 months ago 14
JSON Question

Converting array of objects and nested array to JSON

I have an API endpoint that expects the following json string (this is an example).

"userid": "1234",
"bookshelf": "3",
"bookcount": "6",
{"bookid": "1"},
{"bookid": "2"},
{"bookid": "3"},
{"bookid": "6"}

The api accesses each in the following manner:

$userid = $data['userid'];
$bookshelf = $data['bookshelf'];

I can also loop through the books and get each bookid with:


When I send the above json string via a tool like postman it works fine. I'm having trouble manufacturing this same json string on the javascript side. This is how I populate the data on the front end of my site.

var data = new Array();
data.push({ "userid": "1234" });
data.push({ "bookshelf": "3" });
data.push({ "bookcount": "6" });
data.push({ "books": selectedbooks }); // This is an array of bookid objects

The problem is whether I json.stringify it and send to the webserver and over to the api or have the webserver json_encode, I end up with numeric indexes that can only be accessed like
once it's decoded by the api, which differs from how the api is working. This would require the json string to be assembled in an exact sequence if the api supported it.

How do I go about getting this data in the required format?


The numeric indexes are coming because you're preparing the data as an array, not an object. Arrays in JavaScript are indexed, not associative. Try:

var data = {
    userid: 1234,
    bookshelf: 3,
    bookcount: 6,
    books: selectedbooks