JavaScript中解析JSON对象数组

4

我有一个 JSON 字符串:

{
    "country": "Mauritius",
    "provinces": [
        "mainland"
    ],
    "timeline": {
        "cases": {
            "3/19/20": 3,
            "3/20/20": 12,
            "3/21/20": 14,
            "3/22/20": 28,
            [...]
            "4/17/20": 324
        },
        "deaths": {
            "3/19/20": 0,
            "3/20/20": 0,
            "3/21/20": 1,
            "3/22/20": 2,
            [...]
            "4/17/20": 9
        },
        "recovered": {
            "3/19/20": 0,
            "3/20/20": 0,
            "3/21/20": 0,
            "3/22/20": 0,
            [...]
            "4/17/20": 108
        }
    }
}

我想要实现的是将JavaScript中的cases、deaths和recovered的值解析为独立数组。例如,我希望找到cases数量上与前一天的差异,以3/19/20作为起始日期,初始cases为3。我希望对死亡人数和恢复情况应用相同的逻辑。因此,3/20/20应该有一个值为9(12-3)。
最后,我想将每个值存储在数组中,以便在图表上使用这些数据。请问有人能帮我在JavaScript或JQuery中解析这些数据吗?

$.getJSON('https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30', function(data) {

  let result = data.map(function(e) {
    return {
      cases: e.timeline.cases,
      deaths: e.timeline.deaths,
      recovered: e.timeline.recovered
    };
  }).reduce(function(acc, e) {

    Object.keys(e).forEach(function(t) {
      Object.keys(e[t]).forEach(function(d) {
        acc[t][d] = (acc[t][d] || 0) - e[t][d];
      });
    });
    return acc;
  }, {
    deaths: {},
    recovered: {},
    cases: {}
  });
  console.log(result)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


2
欢迎来到 Stack Overflow!请仔细阅读帮助中心,特别是如何提出好问题? 在这里,您最好的选择是进行研究,在 SO 上搜索相关主题,并尝试一下。如果您遇到困难并且在进行更多研究和搜索后无法解决,请发布一个最小可重现示例,说明您卡在了哪里。人们会很乐意帮助您。 - palaѕн
1
我不理解这句话:“3/20/20应该有一个值为4(3-12)”,怎么会12-3等于4呢? - palaѕн
1
前一天是3,到了3/20/20就变成了12,那么“_3/20/20应该有一个值为4_”的情况是如何实现的? - palaѕн
我在控制台中看到了这个(index):135 Uncaught TypeError: data.map is not a function ,真糟糕。 - CadaMerx
是的,你需要从 Object.keys(data.timeline).map 开始。 - mplungjan
显示剩余8条评论
3个回答

4
以下代码使用 Array#reduce 方法将从服务器返回的绝对值转换为天数之间的差异。

const entries = Object.entries, log = console.log, toJSON = JSON.stringify

const Δ = (arr, prev = 0) => 
  arr.reduce((acc, [date, curr]) => 
    (acc[date] = curr - prev, prev = curr, acc), {})
  
const AUTHORITY = 'corona.lmao.ninja'
async function fetchDeltas({ country, days = 30 }) {  
  const url = `//${AUTHORITY}/v2/historical/${country}?lastdays=${days}`
  const { timeline: { cases, deaths, recovered } } = await (await fetch(url)).json()
  return { 
    newCases: Δ(entries(cases)), 
    newDeaths: Δ(entries(deaths)),
    newRecoveries: Δ(entries(recovered))
  }
}
fetchDeltas({ country: 'mauritius' }).then(log)


我该如何获取最初的案例数量? - CadaMerx
我不理解这个问题。初始案例数量是案例对象中的第一个属性。 - Ben Aston
在newCases中,我也想要包含这个3/19/20: 3。因为这是我们开始收到病例的第一天。 - CadaMerx
1
有趣的函数命名方式 :) - mplungjan

3

(async function() {
const {cases, deaths} = (await (await
fetch("https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30")).json()).timeline;
console.log("Cases", diffEvents(cases));
console.log("Deaths", diffEvents(deaths));
})();

const diffEvents = (value) => {
const dates = Object.keys(value);

return dates.map((date, index) => {
  const currentDate = date;
  const prevDate = dates[index-1];
  return {
        date: currentDate,
        count: index>0 ? value[date] - value[dates[index-1]] : value[date]
       };
   });
 };
 


这个做了什么?为什么要嵌套 await? - mplungjan
1
嵌套的 await 是必要的,因为 json 方法是异步的。 - Ben Aston

2

$.getJSON('https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30', function(data) {
    function fn(x, i) {
        return [this[i][0], this[i][1] - (i-1<0 ? 0 : this[i-1][1])];
     }
console.log(
       Object.fromEntries(
         Object.entries(data.timeline).map( ({0: type, 1: values}) =>
            [ type, Object.fromEntries(
                      (x=Object.entries(values)).map( fn.bind(x) )
                     )] ) )
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接