简体   繁体   中英

Iterate over JSON Object using Python

I have a JSON object and was wondering how I can iterate over the object to pull values for "id".

{
"totalSize": 5,
"done": true,
"records": [
    {
        "attributes": {
            "type": "EventLogFile",
            "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA"
        },
        "Id": "0AT1U000003kk7dWAA"
    },
    {
        "attributes": {
            "type": "EventLogFile",
            "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7eWAA"
        },
        "Id": "0AT1U000003kk7eWAA" 

I was trying something below.

sub_data = s["records"]["id"]
for i in sub_data:
        print(sub_data['id'])

You can iterate through the records key as a list and then access the Id key of each sub-dict:

for i in s["records"]:
    print(i['Id'])
s = """{ "totalSize": 5, 
        "done": true, "records": [ 
            { "attributes": { 
                "type": "EventLogFile", 
                "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA" }, 
                "Id": "0AT1U000003kk7dWAA" } 
        ] 
    }"""
s = json.loads(s)

[r['Id'] for r in s['records']]

['0AT1U000003kk7dWAA']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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