javascript - 我如何操作 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 中处理它。
解决方案
您可以尝试在应用程序中使用 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));
推荐阅读
- java - 无法在 Kotlin 中使用协程(未解决的参考)
- stimulsoft - 没有加载 StimulSoft Report svgs 的问题
- c# - .Net Core 3.1 的池化数据库上下文
- styled-components - 带有样式组件的滑动按钮样式
- javascript - Mongodb 注册重新运行成功,但是当我登录用户时它返回错误。我正在使用 Postman 来测试 Api
- javascript - 为什么使用map、forEach和for循环将数组插入数据库时的顺序不同
- android - Android CameraX 分析器,启用手电筒没有任何作用
- python - 如何在烧瓶的新标签中打开pdf
- wordpress - 嵌套自定义块以允许多次使用 innerBlocks
- python - 在 Django 中使用 Knox Token 从 DRF Token 中的令牌字符串获取用户对象