登录
首页 >  文章 >  前端

如何将包含动态键名的 JSON 字符串解析成键值对类型?

时间:2024-11-01 11:36:47 207浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个文章开发实战,手把手教大家学习《如何将包含动态键名的 JSON 字符串解析成键值对类型?》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

如何将包含动态键名的 JSON 字符串解析成键值对类型?

关于一个动态 json 字符串的解析问题

问题

我们从后台获取到一个包含动态键名的 json 字符串,需要将其解析成一个 javascript 类型,该类型包含一个键值对,其中键是动态键名,值是键名对应的值。

问题示例

给定以下 json 字符串:

[
  {
    "name": "2015年",
    "stattotal": [
      {
        "total": "123",
        "stattype": "事件等级"
      },
      {
        "total": "456",
        "stattype": "行政区域"
      }
    ]
  },
  {
    "name": "2016年",
    "stattotal": [
      {
        "total": "789",
        "stattype": "事件等级"
      },
      {
        "total": "110",
        "stattype": "行政区域"
      }
    ]
  },
  {
    "name": "2017年",
    "stattotal": [
      {
        "total": "128",
        "stattype": "事件等级"
      },
      {
        "total": "654",
        "stattype": "行政区域"
      }
    ]
  }
]

目标是将其解析成一个类型为:

{
  "事件等级": ["123", "789", "128"],
  "行政区域": ["456", "110", "654"]
}

解决方案

function parsedynamicjson(data) {
  const result = json.parse(data);
  const map = new map();

  // 遍历 json 对象
  for (const item of result) {
    // 遍历 stattotal 数组
    for (const stat of item.stattotal) {
      // 获取 stattype 并添加到 map 中
      const stattype = stat.stattype;
      if (!map.has(stattype)) {
        map.set(stattype, []);
      }

      // 将 total 添加到 map 中
      const totalarray = map.get(stattype);
      totalarray.push(stat.total);
    }
  }

  // 返回 map 作为 javascript 对象
  return object.fromentries(map.entries());
}

使用方法

const jsonString = '[...JSON string from example...]';
const resultObject = parseDynamicJson(jsonString);
console.log(resultObject); // 输出:{ "事件等级": ["123", "789", "128"], "行政区域": ["456", "110", "654"] }

今天关于《如何将包含动态键名的 JSON 字符串解析成键值对类型?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>