Home > Back-end >  how to capture data from json?
how to capture data from json?

Time:10-23

I have a text in json format:

'{"Info":{"Result":"OK","ID":8840,"FamilyName":"book","Title":"A950","Model":"A-A","Name":"A 5","Img":"A950-A.png"}}'

how do I capture the "Img" field I'm trying to print(json.loads(response.text['Info']['Img'])) but I get an error: string indices must be integers

CodePudding user response:

You're json.loads()ing the wrong thing.

At the moment you're trying to index the string as if it were already parsed into Python data structures and then passing the result into json.loads():

print(json.loads(response.text['Info']['Img']))
#                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Instead, parse the whole response as JSON and then index into it:

print(json.loads(response.text)['Info']['Img'])
#     ^^^^^^^^^^^^^^^^^^^^^^^^^

CodePudding user response:

use HLXJSON. I made it. You can put the json into a file eg: test.json Import hlxjson by:

pip import HLXJSON

And code:

import hlxjson
f = open("test.json","w")
f.write(response.text)
f.close()
a = hlxjson.readdiv("test.json","info","img")
print(a)

Read hlxjson docs too https://pypi.org/project/HLXJSON/ Use f.write(response) instead of f.write(response.text) if it doesnt work. (Sorry if it doesnt help)

  • Related