Handlebars中解析JSON字符串并遍历数组的实现方案求助
问题描述
现有如下格式的数据:
{ "data" : [ { "query": "Hello", "response": "asad" }, { "query": "Tell Weather dale", "response": "[{\"datetime\":\"2024-01-26\",\"tempmax\":21.5,\"tempmin\":7,\"temp\":14,\"humidity\":59.2,\"precip\":0,\"precipprob\":0,\"windspeed\":5.8,\"cloudcover\":61.6,\"conditions\":\"Partially cloudy\"},{\"datetime\":\"2024-01-27\",\"tempmax\":23.2,\"tempmin\":11.2,\"temp\":16.3,\"humidity\":38.2,\"precip\":0,\"precipprob\":0,\"windspeed\":9.4,\"cloudcover\":32.5,\"conditions\":\"Partially cloudy\"},{\"datetime\":\"2024-01-28\",\"tempmax\":24,\"tempmin\":11.7,\"temp\":17.2,\"humidity\":39.9,\"precip\":0,\"precipprob\":0,\"windspeed\":10.4,\"cloudcover\":54.9,\"conditions\":\"Partially cloudy\"},{\"datetime\":\"2024-01-29\",\"tempmax\":25,\"tempmin\":12.6,\"temp\":18.2,\"humidity\":42.1,\"precip\":0,\"precipprob\":0,\"windspeed\":9.7,\"cloudcover\":41.3,\"conditions\":\"Partially cloudy\"},{\"datetime\":\"2024-01-30\",\"tempmax\":25.3,\"tempmin\":13.8,\"temp\":18.8,\"humidity\":48.2,\"precip\":0,\"precipprob\":0,\"windspeed\":6.1,\"cloudcover\":66.5,\"conditions\":\"Partially cloudy\"},{\"datetime\":\"2024-01-31\",\"tempmax\":26.2,\"tempmin\":14.6,\"temp\":19.5,\"humidity\":48.4,\"precip\":0,\"precipprob\":0,\"windspeed\":9.4,\"cloudcover\":14.9,\"conditions\":\"Clear\"}]" } ] }
其中response字段可能是普通字符串或JSON字符串,需解析JSON字符串并遍历数组展示datetime、temp等字段,目前已能解析JSON但无法在Handlebars模板中完成遍历,需实现对应的模板及Helper函数。
解决方案
1. 注册Handlebars Helper函数
需要两个Helper:一个用于解析JSON字符串,另一个用于判断是否为数组。
解析JSON的Helper
Handlebars.registerHelper('parseJson', function(jsonString) { try { return JSON.parse(jsonString); } catch (error) { // 解析失败,返回原字符串 return jsonString; } });
判断数组的Helper
Handlebars.registerHelper('isArray', function(value) { return Array.isArray(value); });
2. Handlebars模板实现
模板会遍历数据列表,自动识别response类型:若是JSON数组则生成表格展示字段,若是普通字符串则直接显示。
{{#each data}} <div class="chat-entry"> <strong>Query:</strong> {{query}} {{#with (parseJson response) as |parsedData|}} {{#if (isArray parsedData)}} <table style="margin-top: 8px; border-collapse: collapse;"> <thead> <tr style="border-bottom: 1px solid #ddd;"> <th style="padding: 8px;">日期</th> <th style="padding: 8px;">温度(°C)</th> <th style="padding: 8px;">天气状况</th> <th style="padding: 8px;">湿度(%)</th> </tr> </thead> <tbody> {{#each parsedData}} <tr style="border-bottom: 1px solid #eee;"> <td style="padding: 8px;">{{datetime}}</td> <td style="padding: 8px;">{{temp}}</td> <td style="padding: 8px;">{{conditions}}</td> <td style="padding: 8px;">{{humidity}}</td> </tr> {{/each}} </tbody> </table> {{else}} <p style="margin-top: 4px;"><strong>Response:</strong> {{parsedData}}</p> {{/if}} {{/with}} <hr style="margin: 16px 0;" /> </div> {{/each}}
说明
parseJsonHelper会尝试将response解析为JSON,失败则返回原字符串;isArrayHelper判断解析后的内容是否为数组,以此决定渲染方式;- 模板中用
#with接收解析后的结果,再通过#each遍历数组生成表格,普通字符串则直接输出。
内容的提问来源于stack exchange,提问作者amit.s19
相关产品推荐
相关产品推荐

