简体   繁体   English

解析嵌套的JSON数据

[英]Parsing nested JSON data

This JSON output is from a MongoDB aggregate query. 此JSON输出来自MongoDB聚合查询。 I essentially need to parse the nested data JSON down to the following to the ' total' and '_id' values. 我本质上需要将嵌套数据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 json and simplejson modules. 我尝试了5种不同的技术来从中获得所需的信息,但是使用jsonsimplejson模块遇到了问题。

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. 注意:来自MongoDB的JSON响应实际上无效。 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: 我不确定为什么您的响应具有单引号而不是双引号,但是从其外观上,您可以替换它们,然后仅使用内置的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'])

Your example text is not valid JSON text . 您的示例文本不是有效的JSON文本 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字符串必须以启动"引号 ,不是' ,但它似乎是一个有效的Python文字,您可以用解析ast.literal_eval()函数

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 json module to parse it. 更好的方法可能是修复查询过程以获取有效的JSON并使用json模块对其进行解析。

The response you are getting from the mongodb seems to be the compatible to put for the dictionary type object. 您从mongodb获得的响应似乎与字典类型对象兼容。 as

{
    '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. 不能将其放入多行字符串并用双引号代替单引号,我们不能直接将其分配给dict类型对象。 and perform further operation on it like: 并对它执行进一步的操作,例如:

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'])
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 这应该工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM