解析嵌套的JSON数据 [英] Parsing nested JSON data

查看:427
本文介绍了解析嵌套的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此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种不同的技术来获取所需的信息,但是使用jsonsimplejson模块遇到了问题.

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数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆