From a request I have a given variable like
realname = "Toni Toni"
I have a structured JSON which I call with
with urllib.request.urlopen("https://api.webside") as url:
data = json.loads(url.read().decode())
The structure is like
{
"status": 200,
"result": {
"accountStatistics": [{
"account": {
"name": "Toni Toni",
"handle": "toni.k",
},
}, {
"account": {
"name": "Gina",
"handle": "katja.k",}]
...}}
What I want is: when my given var "realname" matches with any of the variables "name" in the JSON then create a new variable "username" which contents the string of the variable "handle" (suitable to the "name" it belongs) so that my result is:
realname = "Toni Toni"
username = "toni.k"
I found code examples but I am not able to transfer it to my specific problem. I am new to Python. Can somebody help me please?
I tried this one to access, but I got a TypeError: list indices must be integers or slices, not str:
for ["account"]["name"] in data["result"]["accountStatistics"]:
if ["name"] ==realname:
username = account["name"]
print(username)
for account in data.result.accountStatsitics: if account.name ==realname: username=account.name breakdoes this work?data["result"]["accountStatistics"]-but not sure if it is the best way. your thoughts look like what I want, but when I tried this code I gotfor account in data.result.accountStatistics: AttributeError: 'dict' object has no attribute 'result'username = data["result"]["accountStatistics"][0]["account"]["handle"] print(username)- but in the end I will have different "realnames" and have to find for all the "realnames" the suitable "handles" (which I will call "username" then)["account"]is just a list containing the literal stringaccountand is completely unrelated to the variable you are looping over.account["name"]not["account"]["name"]-- I have not examined the structure in more detail but this should at least provide a starting point.