Home > database >  Get fields from a JSON file with Python
Get fields from a JSON file with Python

Time:02-26

I have this json file loaded in Python with json.loads('myfile.json'):

    [
    {
        "cart": {
            "items": {
                "3154ba405e5c5a22bbdf9bf1": {
                    "item": {
                        "_id": "3154ba405e5c5a22bbdf9bf1",
                        "title": "Drink alla cannella",
                        "price": 5.65,
                        "__v": 0
                    },
                    "qty": 1,
                    "price": 5.65
                }
            },
            "totalQty": 1,
            "totalPrice": 5.65
        }
    },
    {
        "cart": {
            "items": {
                "6214ba405e4c5a31bbdf9ad7": {
                    "item": {
                        "_id": "6214ba405e4c5a31bbdf9ad7",
                        "title": "Drink alla menta",
                        "price": 5.65,
                        "__v": 0
                    },
                    "qty": 2,
                    "price": 11.3
                }
            },
            "totalQty": 2,
            "totalPrice": 11.3
        }
    }
]

How I can access to both totalQty and totalPrice fields at same time and sum them?

How I can access to both Title fields to print it?

CodePudding user response:

Let's assume that you have the JSON data available as a string then:

jdata = '''
[
    {
        "cart": {
            "items": {
                "3154ba405e5c5a22bbdf9bf1": {
                    "item": {
                        "_id": "3154ba405e5c5a22bbdf9bf1",
                        "title": "Drink alla cannella",
                        "price": 5.65,
                        "__v": 0
                    },
                    "qty": 1,
                    "price": 5.65
                }
            },
            "totalQty": 1,
            "totalPrice": 5.65
        }
    },
    {
        "cart": {
            "items": {
                "6214ba405e4c5a31bbdf9ad7": {
                    "item": {
                        "_id": "6214ba405e4c5a31bbdf9ad7",
                        "title": "Drink alla menta",
                        "price": 5.65,
                        "__v": 0
                    },
                    "qty": 2,
                    "price": 11.3
                }
            },
            "totalQty": 2,
            "totalPrice": 11.3
        }
    }
]
'''
totalQty = 0
totalPrice = 0
for d in json.loads(jdata):
    c = d['cart']
    totalQty  = c['totalQty']
    totalPrice  = c['totalPrice']
    for sd in c['items'].values():
        print(sd['item']['title'])
print(f'{totalQty:d}', f'{totalPrice:.2f}')

Output:

3 16.95

Note:

I suspect that what you really want to do is multiply those two values

  • Related