将多个JSON响应显示为单个值的HTML
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将多个JSON响应显示为单个值的HTML相关的知识,希望对你有一定的参考价值。
我订阅了一个以JSON格式返回数据的天气API。该数据带有多个值:
{
"success": true,
"error": null,
"response": [
{
"periods": [
{ "snowIN": 0.15 },
{ "snowIN": 0.15 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.18 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.24 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 },
{ "snowIN": 0.03 }
]
}
]
}
我想获取这些值,得到总和并在我的html中显示它。
我怎么做?
在48小时内获得总量降雪量
snowIN
并在html上显示该值作为文本。
我试过这个编码......
<script type="text/javascript" src="https://cdn.aerisapi.com/sdk/js/latest/aerisweather.min.js">
</script>
<script type="text/javascript">
window.onload = () => {
const target = document.getElementById('data-reading');
const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET');
const request = aeris.api().endpoint('forecasts').place('pierre,sd').filter('1hr').limit('48');
request.get().then((result) => {
const data = result.data;
const { periods } = data[0];
if (periods) {
periods.reverse().forEach(period => {
const snowIN = period.snowIN || '0.00';
const html = (`
<p class="map-datavalue">${snowIN}"</p>
`);
target.insertAdjacentHTML('afterbegin', html);
});
}
});
}
</script>
结果显示所有snowIN
值,而不是一个。当我运行html时,我也把我的const aeris = new AerisWeather('CLIENT_ID', 'CLIENT_SECRET')
。
答案
你可以用Array.prototype.reduce()
来做
// Once you have the results
const api_result = {"success":true,"error":null,"response":[{"periods":[{"snowIN":0.15},{"snowIN":0.15},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.18},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.24},{"snowIN":0.03},{"snowIN":0.03},{"snowIN":0.03},{"snowIN":0.03}]}]};
let sum;
try {
// Use reduce to calculate the sum
sum = api_result.response[0].periods.reduce((r, v) => r+v.snowIN, 0);
// JS math is not exact, so we use `toFixed` to only keep 2 decimals
sum = sum.toFixed(2);
} catch(e) {
// In case the data is not complete
sum = "not available";
}
document.getElementById('sum').innerHTML = sum;
<h1>The sum is <span id="sum"></span></h1>
另一答案
您可以像这样访问数据。
const data = {"succes": true, ...}
data.response.map((value, key) => {
// value is mapping to peridos.
})
函数map()可能不是获取数据总和的绝对正确方法,但可以。 (看看MDN)我建议你先用简单的数据练习。
以上是关于将多个JSON响应显示为单个值的HTML的主要内容,如果未能解决你的问题,请参考以下文章
如何将包含逗号分隔的 json 值的单个字符串转换为单个 json 对象?
AJAX 响应:数据(JSON、XML)还是 HTML 片段? [关闭]