how to build json array dynamically in javascript

不羁岁月 提交于 2019-12-02 11:31:58

I am not sure if this has been a course of confusion, but there is no such thing as a "JSON object". One works with data objects returned by JSON.parse in the same manner as working with any other object. Before sending to FB, of course, data objects have to be converted into JSON string format using JSON.stringify. This might occur automatically in some code libraries depending on how the data is sent.

Here's an example of preparing a quick-replies array - I simply chose an example structure for the payload and went with it. The quick_replies array is still an object and has not been converted to a JSON string.

Edit the format of a text only payload, shown in the first text only example for quick replies indicates the payload is a string. The code below had been updated to meet with this requirement.

// test values for quickreplies:

var quickreplies= [ "News?", "Subscribe?", "Contribute?", "Organize?" ];

/********

     convert quickreplies to quick_replies array
     using an example payload of:

     { "text" : "text string",       // button text
       "index" : index,              // index into quickreply for button
       "other": "tbd"                // anything else needed in a reply
     }

*********/
var quick_replies;
if (quickreplies) {
    console.log('we got quickreplies, here they are:');
    quick_replies = quickreplies.map( function(element, index) {

        var payload = {
                text: element,
                index: index,
                other: "tbd"    // example value only.
        };
        var payloadString = JSON.stringify( payload);
        console.log(element);
        var quick_reply = {
            content_type: "text",
            title: element,
            payload: payloadString
        };
        console.log("** converted to : " + JSON.stringify(quick_reply));
    });
    quickreplies=null; // housekeeping
}
else {
    console.log('no quickreplies');
    quick_replies = undefined; // or [] ?
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!