0

I receive a json object with some number of quick reply elements from wit.ai, like this:

 "msg": "So glad to have you back.  What do you want me to do?  
 "action_id": "6fd7f2bd-db67-46d2-8742-ec160d9261c1",
 "confidence": 0.08098269709064443,
 "quickreplies": [
   "News?",
   "Subscribe?",
   "Contribute?",
   "Organize?"
 ],
 "type": "msg"

I then need to convert them to a slightly different format as they are passed to FaceBook Messenger as described in the code below. Wit only exposes 'msg' and 'quickreplies.' Can you suggest a good way to do this? It goes after "console.log(element)" as far as I understand.

      if (quickreplies){
        // got simple array of quickreplies
        // need to format quickreplies for FB:
                                  //  "quick_replies":[
                                  //     {
                                  //       "content_type":"text",
                                  //       "title":"Red",
                                  //       "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
                                  //     },
                                  //     {
                                  //       "content_type":"text",
                                  //       "title":"Green",
                                  //       "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
                                  //     }]
        console.log('we got quickreplies, here they are:');
        var quick_replies = []; // ??
        quickreplies.forEach(function(element) {
          console.log(element)

        });
      }
      else (console.log('no quickreplies'));                               

In the above example, the end result should be this:

  //  "quick_replies":[
  //     {
  //       "content_type":"text",
  //       "title":"News",
  //       "payload":"News"
  //     },
  //     {
  //       "content_type":"text",
  //       "title":"Subscribe?",
  //       "payload":"Subscribe?"
  //     }
  //       "content_type":"text",
  //       "title":"Contribute?",
  //       "payload":"Contribute?"
  //     },
  //     {
  //       "content_type":"text",
  //       "title":"Organize?",
  //       "payload":"Organize?"
  //     }
  //  ]
jeromekjerome
  • 501
  • 1
  • 8
  • 26

2 Answers2

0

Most straightforward way, I think, would be to convert the JSON into an object using JSON.parse().

Then manipulate the object, removing and adding elements as needed.

Once done, using JSON.stringify to convert the object back into a JSON string.

Doug Ross
  • 48
  • 6
0

Maybe this can help you out.

function makeReply(text) {
    return { content_type: 'text', title: text, payload: text };
}

var replies = { quick_replies: [] };
    quickreplies.forEach(function(element) {
      replies.quick_replies.push(makeReply(element); // not sure what needs to be supplied for "title" and "payload"

    });
JohanP
  • 5,252
  • 2
  • 24
  • 34