python - 解析嵌套的 JSON 数据

标签 python json

此 JSON 输出来自 MongoDB 聚合查询。我基本上需要将嵌套数据 JSON 解析为以下“total”“_id” 值。

{
'ok': 1.0, 
'result': [
            {
                'total': 142250.0, 
                '_id': 'BC'
            }, 
            {
                'total': 210.88999999999996,
                 '_id': 'USD'
            }, 

            {
                'total': 1065600.0, 
                '_id': 'TK'
            }
            ]
}

我已经尝试了 5 种不同的技术来获得我需要的东西,但是我在使用 jsonsimplejson 模块时遇到了问题。

理想情况下,输出应该是这样的:

142250.0, BC
210.88999999999996, USD
1065600.0, TK

最佳答案

注意:您来自 MongoDB 的 JSON 响应实际上无效。 JSON 需要双引号 ("),而不是单引号 (')。

我不确定为什么您的响应使用单引号而不是双引号,但从外观上看您可以替换它们,然后只需使用内置的 json 模块:

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'])

关于python - 解析嵌套的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19729710/

相关文章:

python - 用字典删除重复行

json - 在 MS SQL 中过滤数据

python - 如何在Python中设置 basemap 的偏移量?

python - 如何使用 asyncio 和 multiprocess.map 获取数据

javascript - Rails Ajax JS 与 JSON 混淆

javascript - 已回答 : SyntaxError: JSON. 解析:预期为 ':' 但它位于对象的末尾

Python:无法将 'bytes' 对象隐式转换为 str

python - 此消息总是指索引问题?索引错误 : index out of bounds

python - 为什么错误不是python中的tk属性?

python - 当默认目录为python2.7时,如何将beautifulsoup安装到python3中?