Igor Hwang
Igor Hwang

Reputation: 72

Generate JSON in loop

I have quite simple yet complicated question to ask. I'm developing facebook messenger bot and stuck into one issue:

I have JSON file with structure like:

{ 
  itemname1: 'Name1',
  itemaddress1: 'Address1',
  itemtelephone1: 'Telephone1',
  services1: {
    service1name1: 'servicename1',
    service1price1: 'serviceprice2' 
    }
  itemname2: 'Name2',
  itemaddress2: 'Address2',
  itemtelephone2: 'Telephone2',
  services2: {
    service2name1: 'servicename1',
    service2price1: 'serviceprice2' 
    }, {
    service2name1: 'servicename1',
    service2price1: 'serviceprice2' 
    }
}

And I read it from file.json.

Now to message user, I have to generate JSON object in order Facebook to understand it. And the scheme is:

function sendGenericMessage(sender) {
messageData = {
"attachment": {
  "type": "template",
  "payload": {
    "template_type": "generic",
    "elements": [{
      "title": "First card",
      "subtitle": "Element #1 of an hscroll",
      "image_url": "http://messengerdemo.parseapp.com/img/rift.png",
      "buttons": [{
        "type": "web_url",
        "url": "https://www.messenger.com/",
        "title": "Web url"
      }, {
        "type": "postback",
        "title": "Postback",
        "payload": "Payload for first element in a generic bubble",
      }],
    },{
      "title": "Second card",
      "subtitle": "Element #2 of an hscroll",
      "image_url": "http://messengerdemo.parseapp.com/img/gearvr.png",
      "buttons": [{
        "type": "postback",
        "title": "Postback",
        "payload": "Payload for second element in a generic bubble",
      }],
    }]
  }
}

};

So what I am to achieve is to read from database and generate cards by the count of elements. For example, I have itemname1 and itemname2 in my JSON, so this should result in:

"elements": [{ 
   "name": "First card"
   blah-blah
   }, {
   "name": "Second card"
   blah-blah
   }]

The same goes with buttons. Any ideas how to perform it wisely? Oh yes, I'm using Node.JS with Express and LokiJS for DB implementation. (Though it's more JS algorithm question).

Thank you for your time.

Upvotes: 1

Views: 643

Answers (1)

Tudor Constantin
Tudor Constantin

Reputation: 26861

You don't need to create JSON. You have to work with JS objects and then you can either send them to the client as they are, or use JSON.stringify() to have your JSON.

This way, you will have

var elements = [];
//loop through db elements:
elements.push(element_from_db);
//end_loop

then

messageData.payload.elements = elements;

Upvotes: 2

Related Questions