JSON Nested Data Analysis

This JSON output is the result of an aggregated MongoDB request. I essentially need to parse the embedded JSON data to the following values ​​" total'and '_id'.

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

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

I tried 5 different methods to get what I needed from him, however I ran into problems using modules jsonand simplejson.

Ideally, the output would be something like this:

142250.0, BC
210.88999999999996, USD
1065600.0, TK
+4
source share
4 answers

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

, , , 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'])
+8

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

142250.0, BC
210.89, USD
1065600.0, TK

, JSON json .

0
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

-2
source

It has to be done.

import json

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

All Articles