繁体   English   中英

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

[英]how to build json array dynamically in javascript

我从wit.ai收到一个带有一些快速回复元素的json对象,如下所示:

  "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" 

然后,当它们传递到FaceBook Messenger时,我需要将它们转换为稍有不同的格式,如下面的代码所述。 机智只会显示“ msg”和“快速回复”。 您能建议一个好的方法吗? 据我了解,它在“ console.log(element)”之后。

  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')); 

在上面的示例中,最终结果应为:

  "recipient":{ "id":"USER_ID" }, "message":{ "text":"Pick a color:", "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" } ] } 

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

这是准备quick-replies数组的示例-我只是为有效负载选择了示例结构,然后就使用了它。 quick_replies数组仍然是一个对象,尚未转换为JSON字符串。

编辑纯文本负载的格式,如第一个纯文本示例所示,快速回复表示负载是字符串。 下面的代码已更新,可以满足此要求。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM