简体   繁体   中英

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",
    "books":[
        {"bookid": "1"},
        {"bookid": "2"},
        {"bookid": "3"},
        {"bookid": "6"}
]}

The api accesses each in the following manner:

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

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

$data['books'][$i]['bookid']

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 $data[0]['userid']; 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
};

You need to create an object, not an array.

var data = {};
data["userid"] = "1234";
data["bookshelf"] = "3";
data["bookcount"] = "6";
data["books"] = selectedbooks; // This is an array of bookid objects

Your data is not supposed to be an array, it's an object. The only array is in the books property.

var data = {}
data.userid = "1234";
data.bookshelf = "3";
data.bookcount = "6";
data.books = selectedbooks;

or more succintly:

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

You can easily transform your array into the expected object :

var arr = [
    {"userid": "1234"},
    {"bookshelf": "3"},
    {"bookcount": "6"},
    {
       "books":[
         {"bookid": "1"},
         {"bookid": "2"},
         {"bookid": "3"},
         {"bookid": "6"}
    ]}
];
var obj = {} ;
arr.forEach(item => {
  var key = Object.keys(item)[0];
  obj[key] = item[key];
});
console.log(obj); 
//{ userid: '1234',
//  bookshelf: '3',
//  bookcount: '6',
//  books: 
//   [ { bookid: '1' },
//     { bookid: '2' },
//     { bookid: '3' },
//     { bookid: '6' } ] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM