1

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?

quamrana
  • 37,849
  • 12
  • 53
  • 71

1 Answers1

2

I am not sure what the relation between json_header and json_data is. But if your json is

{"__ar":1,"payload":[{"id":"USERID","name":"USERNAME"}]}

so payload is an array of dicts. To access the first (and only) dict in the array you do:

payload = json_objects['payload']
first_elemet = payload[0]
id = first_element['id']
print(id)

or all together, complete and ready to execute:

import json
json_string = '{"__ar":1,"payload":[{"id":"USERID","name":"USERNAME"}]}'
json_objects = json.loads(json_string)
print(json_objects['payload'][0]['id'])

By the way: your original data with the for loop looks scary. If this should be JSON it is strange at least and looks like a bug in whatever backend you are calling.

jonas
  • 1,074
  • 11
  • 11
  • Thanks for being so fast in answering. Unfortunately, it still gives me the same error. I know the code is scary. Infact it is not actually supposed to be called with request... – Cosimo Spezzapane Jul 05 '19 at 11:50
  • I tested it the way I understand your code (see updated answer). If this does not work, please paste a complete runable snippet to reproduce the error. – jonas Jul 05 '19 at 12:02