0

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

2 Answers 2

2

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'])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks!. I did try that and received following errorr: for i in s["records"]: TypeError: string indices must be integers, not str
Glad to be of help. Can you mark this answer as accepted if you find it to be correct? (Click on the grey check mark next to the answer.)
0
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']

6 Comments

Your solutions seem right. Just iterate over list of dictionary.Guess, I still get the same error. s1 = [r['id'] for r in s['records']] TypeError: string indices must be integers, not str
@AshishLal can you add the JSON that triggers this error?
{ "totalSize": 5, "done": true, "records": [ { "attributes": { "type": "EventLogFile", "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA" }, "Id": "0AT1U000003kk7dWAA" }, ] }
It works for me [r['Id'] for r in s['records']] the result is ['0AT1U000003kk7dWAA']
I am sure it works. Not sure why its not working for me
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.