Search code examples
javascriptjsonstringify

Javascript Create Json


I'm trying to create and post a json message in the following format:

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);

basically this will create my json like this:

[{"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}]

how can I do it so that if I want to add some metadata to my json that will not repeat for each item but just at the top ... something like this:

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

so basically the category and type will define the whole items in the json but are not repeated for each item ...


Solution

  • how can I do it so that if I want to add some metadata to my json that will not repeat for each item but just at the top

    Use an object as a wrapper with the meta data and the items array:

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

    I'm assuming there that x and y are variables; if they're meant to be literals, put them in quotes.


    Side note: In JavaScript, there's no reason to use new Object. Just use {}, which does the same thing. You can also put property initializers within it, rather than assigning to properties afterward. Here's your $.each with those changes (and indentation):

    $.each(results, function(index, value){
    
        var item = {
            title: value.Title,
            code: value.Code
        };
    
        listObjects.push(item);
    
    });
    

    You can, of course, combine those:

    $.each(results, function(index, value){
    
        listObjects.push({
            title: value.Title,
            code: value.Code
        });
    
    });
    

    Last but not least: What you're doing with $.each is exactly what $.map is for:

    var listObjects = $.map(results, function(index, value){
        return {
            title: value.Title,
            code: value.Code
        };
    });