json解析嵌套jasn语句报错,解析嵌套的JSON数据

This JSON output is from a MongoDB aggregate query. I essentially need to parse the nested data JSON down to the following to the 'total' and '_id' values.

{

'ok': 1.0,

'result': [

{

'total': 142250.0,

'_id': 'BC'

},

{

'total': 210.88999999999996,

'_id': 'USD'

},

{

'total': 1065600.0,

'_id': 'TK'

}

]

}

I've tried 5 different techniques to get what I need from it, however I've run into issues using the json and simplejson modules.

Ideally, the output will be something like this:

142250.0, BC

210.88999999999996, USD

1065600.0, TK

解决方案

NOTE: Your JSON response from MongoDB is not actually valid. JSON requires double-quotes ("), not single-quotes (').

I'm not sure why your response has single-quotes instead of double-quotes but from the looks of it you can replace them and then just use the built-in json module:

from __future__ import print_function

import json

response = """{

'ok': 1.0,

'result': [

{

'total': 142250.0,

'_id': 'BC'

},

{

'total': 210.88999999999996,

'_id': 'USD'

},

{

'total': 1065600.0,

'_id': 'TK'

}

]

}"""

# JSON requires double-quotes, not single-quotes.

response = response.replace("'", '"')

response = json.loads(response)

for doc in response['result']:

print(doc['_id'], doc['total'])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值