Python 解析嵌套的 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19729710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:27:14  来源:igfitidea点击:

Parsing nested JSON data

pythonjson

提问by andrewwowens

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.

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

{
'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 jsonand simplejsonmodules.

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

Ideally, the output will be something like this:

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

142250.0, BC
210.88999999999996, USD
1065600.0, TK

采纳答案by All Workers Are Essential

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

注意:来自 MongoDB 的 JSON 响应实际上无效。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 jsonmodule:

我不确定为什么你的回复有单引号而不是双引号,但从它的外观来看,你可以替换它们,然后只使用内置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'])

回答by elssar

import json

data = json.loads(mongo_db_json)
result = data['result']
for value_dict in result:
    print '{0}, {1}'.format(value['total'], value['_id'])

This should work

这应该工作

回答by shshank

This should do.

这个应该可以。

import json

def parse_json(your_json):
    to_dict = json.loads(your_json)
    for item in to_dict['results']:
        print item['total']

回答by jfs

Your example text is not valid JSON text. JSON string must start with a "quotation mark, not '; but it seems a valid Python literal that you can parse with ast.literal_eval()function:

您的示例文本不是有效的JSON 文本。JSON 字符串必须以"引号开头,而不是'; 但它似乎是一个有效的 Python 文字,您可以使用ast.literal_eval()function进行解析:

import ast

data = ast.literal_eval(input_string)
for item in data["result"]:
    print("{total}, {_id}".format(**item))

Output

输出

142250.0, BC
210.89, USD
1065600.0, TK

A better way might be to fix the querying process to get valid JSON and use jsonmodule to parse it.

更好的方法可能是修复查询过程以获取有效的 JSON 并使用json模块来解析它。

回答by Jyoti Amage

The response you are getting from the mongodb seems to be the compatible to put for the dictionary type object. as

您从 mongodb 获得的响应似乎与字典类型对象兼容。作为

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

Instead of putting it into multiline string and replacing single quotes in double quotes, can't we directly assign it to the dict type object. and perform further operation on it like:

不是把它放到多行字符串中,用双引号替换单引号,我们不能直接赋值给dict类型的对象。并对其执行进一步操作,例如:

json_data = {
    'ok': 1.0,
    'result':
        [
            {
                'total': 142250.0,
                '_id': 'BC'
            },
            {
                'total': 210.88999999999996,
                '_id': 'USD'
            },
            {
                'total': 1065600.0,
                '_id': 'TK'
            }
    ]
}

And:

和:

for data in json_data['result']:
    print(data['total'], data['_id'])