【问题标题】:How can I change such a JSON parser?如何更改这样的 JSON 解析器?
【发布时间】:2021-10-22 22:43:10
【问题描述】:

请帮助我如何将这样的解析器更改为 JSON 以获得新的服务器响应。

旧服务器响应:

{"names":[{"name":"Oleg","act":0,"total":0},{"name":"Vitya","act":2,"total":2}]}

旧解析器:

names = appData.filter( function(x) { return skipped.indexOf(x) < 0; })
        get("https://serv.io/set?" + names.join("|")).then(function(data) {
          result = JSON.parse(data)["names"]
          for (var i = 0; i < result.length; i++) {
            name = result[i]["name"]
            act = result[i]["act"]
            total = result[i]["total"]
          }

新的服务器响应:

{"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}

正如您在新答案中看到的那样,据我所知,没有数组,这里的名称是对象的名称。 问题是如何为新的服务器响应更改旧的解析器。 非常感谢您的帮助!

【问题讨论】:

    标签: javascript json web


    【解决方案1】:

    您可以通过for...in 迭代对象上的键。 destructuring assignment 也可用于此类数据处理。

    const result = {"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}
    
    for (const key in result) {
      const name = key
      const {act, total} = result[key]
      
      console.log(name, act, total)
    }

    请注意,for..in 迭代不会保留返回的 JSON 中包含的元素的顺序。

    不保证for...in 会以任何特定顺序返回索引。

    (来自上述for..in 参考。)

    如果元素的顺序对您的系统很重要,您需要考虑使用另一个 JSON 解析器而不是内置的 JSON.parse() 方法。

    【讨论】:

    • 你知道snippets?吗(你不需要小提琴。)
    • @msanford 不知道。我用 sn-p 更新了我的答案。谢谢!
    【解决方案2】:

    模拟新的响应服务器:

    // New server response
    const data = JSON.stringify({"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}})
    
    // Assuming that you have already the variables declared
    let name;
    let act;
    let total;
    
    // Parse the JSON and work with it
    const result = JSON.parse(data)
    
    // Save this result in a variable, to avoid use Object.entries everywhere.
    const names = Object.entries(result);
    
    // This will be your new loop
    for (var i = 0; i < names.length; i++) {
      name = names[i][0];
      act = names[i][1].act;
      total = names[i][1].total
      console.log(name, act, total);
    }
    

    这将是循环中每次的输出:

    Oleg 0 0
    Vitya 2 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      相关资源
      最近更新 更多