简体   繁体   English

将对象数组和嵌套数组转换为JSON

[英]Converting array of objects and nested array to JSON

I have an API endpoint that expects the following json string (this is an example). 我有一个API端点,需要以下json字符串(这是一个示例)。

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

The api accesses each in the following manner: api以以下方式访问每个:

$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. 当我通过邮递员之类的工具发送上述json字符串时,效果很好。 I'm having trouble manufacturing this same json string on the javascript side. 我在JavaScript端无法制造相同的json字符串。 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']; 问题是我是用json.stringify并将其发送到Web服务器再发送到api还是使用Web服务器json_encode,所以我最终得到只能像$data[0]['userid'];这样访问的数字索引$data[0]['userid']; once it's decoded by the api, which differs from how the api is working. 一旦由api解码,则与api的工作方式不同。 This would require the json string to be assembled in an exact sequence if the api supported it. 如果api支持的话,这将要求json字符串以正确的顺序进行组装。

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. JavaScript中的数组是索引的,而不是关联的。 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. 唯一的数组在books属性中。

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' } ] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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