且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JavaScript中动态构建json数组

更新时间:2023-01-16 19:42:02

我不确定这是否引起混淆,但是没有"JSON对象"之类的东西.一个对象使用JSON.parse返回的数据对象的方式与处理任何其他对象的方式相同.当然,在发送到FB之前,必须使用JSON.stringify将数据对象转换为JSON字符串格式. 可能会在某些代码库中自动发生,具体取决于数据的发送方式.

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.

这是准备quick-replies数组的示例-我只是为有效负载选择了示例结构并进行了处理. quick_replies数组仍然是一个对象,尚未转换为JSON字符串.

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 [] ?
}