首页 > 解决方案 > 我如何操作 json 值

问题描述

我有一个rest api,它返回数据库查询的json&json看起来像

{"keys": "[{'aht': Decimal('238'), 'month': 'April '}, {'aht': Decimal('201'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}

所以从下面

{'aht': Decimal('238'), 'month': 'April '}

删除小数()

预期的:

{'aht': '238', 'month': 'April '}

我可以在 python 3.6 或 js 中处理它。

标签: javascriptpythonjsonpython-3.x

解决方案


您可以尝试在应用程序中使用 JSON 字符串之前对其进行预处理,如下所示。

或者,如果您希望 REST API 发送此输出以与其他内容一起使用,而唯一的问题是 JS/Python(当您想将其作为 JSON 处理时),请为您的 REST 端点实现一个参数以指定是否清理(JSON 格式) 必要与否。基于该参数,在服务器端进行必要的处理以删除 Decimal 等。

let str = `{"keys": "[{'aht': Decimal('2'), 'month': 'April '}, {'aht': Decimal('20'), 'month': 'August '}, {'aht': Decimal('236'), 'month': 'December '}, {'aht': Decimal('230'), 'month': 'February '}, {'aht': Decimal('228'), 'month': 'January '}, {'aht': Decimal('202'), 'month': 'July '}, {'aht': Decimal('201'), 'month': 'June '}, {'aht': Decimal('239'), 'month': 'March '}, {'aht': Decimal('214'), 'month': 'May '}, {'aht': Decimal('235'), 'month': 'November '}, {'aht': Decimal('221'), 'month': 'October '}, {'aht': Decimal('147'), 'month': 'September'}]", "success": true}`;

let cleanJSON = str.replace(/Decimal\('([0-9]*)'\)/g, function(x) {
  return x.substring(9, x.length - 2);
});

console.log(JSON.parse(cleanJSON));


推荐阅读