0

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)
11
  • 1
    for account in data.result.accountStatsitics: if account.name ==realname: username=account.name break does this work? Commented Jan 7, 2021 at 9:42
  • not really, have I to keep attention with the dots? I mostly assign the values with 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 got for account in data.result.accountStatistics: AttributeError: 'dict' object has no attribute 'result' Commented Jan 7, 2021 at 9:54
  • I know that I can assign the "username" by 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) Commented Jan 7, 2021 at 9:58
  • 1
    Because ["account"] is just a list containing the literal string account and is completely unrelated to the variable you are looping over. Commented Jan 7, 2021 at 10:09
  • 1
    You want account["name"] not ["account"]["name"] -- I have not examined the structure in more detail but this should at least provide a starting point. Commented Jan 7, 2021 at 10:14

2 Answers 2

1

getUsernameOf(realname, data) takes two arguments, the name to look for and the JSON to search.

import json

handle = open('./data.json')
data = json.load(handle)

def getUsernameOf(realname, data):
    # Match accountStatistics and map over this
    # capturing all `account` objects into a list
    accounts = [x['account'] for x in data['result']['accountStatistics']]
    for account in accounts:
        if account['name'] == realname:
            return account
    return None

Using:

{
    "status": 200,
    "result": {
        "accountStatistics": [
            {
                "account": {
                    "name": "Toni Toni",
                    "handle": "toni.k"
                }
            },
            {
                "account": {
                    "name": "Gina",
                    "handle": "katja.k"
                }
            }
        ]
    }
}

as data.json, then running with:

print(getUsernameOf("Toni Toni", data))
> {'name': 'Toni Toni', 'handle': 'toni.k'}
Sign up to request clarification or add additional context in comments.

8 Comments

I think it works, one question: can the variable "realname" exists outside of the def? actually I got back a "None"
That means it didn't find the name. Don't be tempted to use global variables; instead, have the function return whatever you need the caller to know, and assign it to a variable in the caller's scope if you need to remember it.
@Chrissi It's very strange you got back None. I've posted a complete example, short of the JSON -- all I did to that was to close it, it is exactly the same.
@kulvin yeah I am sure your code works, I think it's another very basic problem I didn't find. my data base (the JSON) is from a website api and I simplified the JSON for my question to not spam with a large JSON...
@Chrissi I posted the exact JSON that I am using.
|
1

The thing after for should be the name of a new variable which will contain the next value that you are looping over in each iteration.

for account in data["result"]["accountStatistics"]:
    if account["name"] == realname:
        username = account["name"]
        print(username)
        break  # perhaps

Here, we are creating a new variable account which will successively take on each value from the list (array) data["result"]["accountStatistics"] for the duration of the body of the loop. (When the loop exits, it will refer to the last value it had within the loop. I suggest you break out of the loop when you find the value you are looking for if you are certain that it will be unique, or you only need the first hit.)

To see what Python is doing, maybe add print(account) right inside the for loop; you should be able to observe how the variable takes on a new value from the array each time. (Of course, take out the print when you are done debugging.)

1 Comment

wow, thanks for the very nice explanation :-)

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.