Create a JSON and add elements dynamically

Asked

Viewed 550 times

1

I wanted to know how to create a JSON and then add elements dynamically.

The initial JSON needs to be like this:

{
        id: Lime.Guid(),
        type: "application/vnd.lime.collection+json",
        to: "[email protected]",
        content: {
            itemType: "application/vnd.lime.document-select+json",
            items: [ ] 
        } 
}

So I need to go adding elements in Items dynamically, based on an array I have. Each item will be of the form:

{
    header: {
      type: "application/vnd.lime.media-link+json",
      value: {
        title: "Title",
        text: "This is a first item",
        type: "image/jpeg",
        uri: "http://www.isharearena.com/wp-content/uploads/2012/12/wallpaper-281049.jpg"
       }
    }
}

I create it as follows in my code:

messageCarousel =  '{ ' +
            'id: Lime.Guid(), ' +
            'type: "application/vnd.lime.collection+json",' +
            'to: "[email protected]",' +
            'content: { ' +
                'itemType: "application/vnd.lime.document-select+json", ' +
                'items: [ ] '+ 
            '}' ;

And then I add the Items:

var obj = JSON.parse(messageCarousel);
messageCarousel[items].push('{ header: ' +
    ' { type: "application/vnd.lime.media-link+json", ' +
    'value: { ' +
    'title: Name, ' +
    'type: "image/jpeg", ' +
    'uri: Uri }}' );
messageCarousel = JSON.stringify(obj);

Can someone tell me what’s wrong and how I should do it in the best way?

1 answer

3


You don’t need to create the json as a string for later parsing.

// somente para mock
var Lime = { 

  Guid: function () {
    return '123456789'
  }
};

var messageCarousel  = {
  id: Lime.Guid(),
  type: "application/vnd.lime.collection+json",
  to: "[email protected]",
  content: {
      itemType: "application/vnd.lime.document-select+json",
      items: [ ] 
  } 
};

// add um item nos items
messageCarousel.content.items.push({
    header: {
      type: "application/vnd.lime.media-link+json",
      value: {
         title: "Title",
         text: "This is a first item",
         type: "image/jpeg",
         uri: "http://www.isharearena.com/wp-content/uploads/2012/12/wallpaper-281049.jpg"
      }
   }
});

// debug
alert('Veja o console para mais detalhes');
console.log(messageCarousel);
  
  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.