1

我正在尝试以以下格式创建和发布 json 消息:

var listObjects = [];

$.each(results, function(index, value){

var item = new Object();
item.title = value.Title;
item.code = value.Code;

listObjects.push(item);

});

var jsonResult = JSON.stringify(listObjects);

基本上这将像这样创建我的json:

[{"title":"Product 1","code":123456789012},
{"title":"Product 2","code":123456789012},
{"title":"Product 3","code":123456789012},
{"title":"Product 4","code":123456789012},
{"title":"Product 5","code":123456789012},
{"title":"Product 11","code":123456789012},
{"title":"Product 12","code":123456789012},
{"title":"Product 13","code":123456789012}]

我该怎么做才能做到这一点,如果我想向我的 json 添加一些元数据,这些元数据不会对每个项目重复,而是在顶部......就像这样:

category: x
type:   y
...
   items:
         title: .....
         code: ......

所以基本上类别和类型将定义json中的整个项目,但不会为每个项目重复......

4

2 回答 2

3

我怎么能这样做,如果我想向我的 json 添加一些元数据,这些元数据不会对每个项目重复,而是在顶部

使用对象作为元数据和items数组的包装器:

var jsonResult = JSON.stringify({
    category: x,
    type:     y,
    items:    listObjects
});

我假设那里xy变量;如果它们是文字,请将它们放在引号中。


旁注:在 JavaScript 中,没有理由使用new Object. 只需使用{},它做同样的事情。您还可以将属性初始化器放入其中,而不是事后分配给属性。这是您$.each的这些更改(和缩进):

$.each(results, function(index, value){

    var item = {
        title: value.Title,
        code: value.Code
    };

    listObjects.push(item);

});

当然,您可以结合这些:

$.each(results, function(index, value){

    listObjects.push({
        title: value.Title,
        code: value.Code
    });

});

最后但并非最不重要的一点:您所做$.each的正是$.map为了:

var listObjects = $.map(results, function(index, value){
    return {
        title: value.Title,
        code: value.Code
    };
});
于 2013-08-18T13:36:52.580 回答
0

只需创建一个对象

var data={};
// your header
var header={category: x,type: y};
//your jsonresult
var jsonResult= [{"title":"Product 1","code":123456789012},
{"title":"Product 2","code":123456789012},
{"title":"Product 3","code":123456789012},
{"title":"Product 4","code":123456789012},
{"title":"Product 5","code":123456789012},
{"title":"Product 11","code":123456789012},
{"title":"Product 12","code":123456789012},
{"title":"Product 13","code":123456789012}]

data.heade=header;
data.result=jsonResult;

your data should be {header:{category: x,type: y},
jsonResult:[{"title":"Product 1","code":123456789012},
    {"title":"Product 2","code":123456789012},
    {"title":"Product 3","code":123456789012},
    {"title":"Product 4","code":123456789012},
    {"title":"Product 5","code":123456789012},
    {"title":"Product 11","code":123456789012},
    {"title":"Product 12","code":123456789012},
    {"title":"Product 13","code":123456789012}]
}
于 2013-08-18T13:42:16.860 回答