如何将包含动态键名的 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 字符串解析成键值对类型?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1494803.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 16:52:47
下一篇 2025年12月19日 16:52:59

相关推荐

发表回复

登录后才能评论
关注微信