Parsing nested JSON data

后端 未结 5 2029
执笔经年
执笔经年 2020-12-18 05:57

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

5条回答
  •  旧巷少年郎
    2020-12-18 06:18

    The response you are getting from the mongodb seems to be the compatible to put for the dictionary type object. 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. 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'])
    

提交回复
热议问题