Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am struggling trying to extract keys from a JSON output.

requests outputs this JSON:

for (;;);{"__ar":1,"payload":[{"id":"USERID","name":"USERNAME"}]}

at this point I get rid of "for (;;);" in order to get a valid JSON:

json_header = (data.text).replace('for (;;);', '')

Now I need to print USERID and USERNAME. This is what I try:

json_data = json.dumps(json_header)

json_objects = json.loads(json_data)

print(json_objects['payload']['id'])

But I get this:

TypeError: string indices must be integers

Can you help me fix the code?

1 Answer

0 votes
by (25.1k points)

Since payload is an array of dictionary you can do it like this:

payload = json_objects['payload']

first_elemet = payload[0]

id = first_element['id']

print(id)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...