How to fix local variable 'id' referenced before assignment

Question:

I want to get a variable from a JSON file to python but it says that the local variable ‘id’ is referenced before assignment

def getInfo(name):
    with open("data.json") as file:
        file_data = json.load(file)

    for i in file_data["data"]:
        if i["name"] == name:
            id = i["id"]

    return id
Asked By: EZDJSkdjs

||

Answers:

id is actully defined only in the for loop scope, so define it at the getInto scope so you could return it

class Info:

    def __init__(self):
        pass
    def getInfo(self,name):
        with open("data.json") as file:
            file_data = json.load(file)
        id=None # <<< here
        for i in file_data["data"]:
            if i["name"] == name:
                id = i["id"]


        return id

Answered By: Eliav Louski

No need to specify a constructor if you don’t do anything in it.

getInfo() stops iterating when it finds the id
No need to keep on looping once it has been found.

class Info:
    def getInfo(self,name):
        with open("data.json") as file:
            file_data = json.load(file)
            for i in file_data["data"]:
                if i["name"] == name:
                    return i["id"]
        return None
Answered By: 0x0fba
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.