问题描述
此JSON输出来自MongoDB聚合查询.我基本上需要将嵌套数据JSON解析为以下的total'
和'_id'
值.
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'
}
]
}
我尝试了5种不同的技术来获取所需的信息,但是使用json
和simplejson
模块遇到了问题.
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
推荐答案
注意:您来自MongoDB的JSON响应实际上无效. JSON需要双引号("
),而不是单引号('
).
NOTE: Your JSON response from MongoDB is not actually valid. JSON requires double-quotes ("
), not single-quotes ('
).
我不确定您的响应为什么使用单引号而不是双引号,但是从其外观上,您可以替换它们,然后仅使用内置的json
模块:
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'])
这篇关于解析嵌套的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!