Home > Blockchain >  "import json" doesn't import the json.loads() function (I'm working with Flask h
"import json" doesn't import the json.loads() function (I'm working with Flask h

Time:07-05

I'm using Flask on Visual Studio Community 2022 and I'm trying to access a json file and return the object. Here's my code :

import json

app = Flask(__name__)

@app.route('/')
def index():
    return "Index"

@app.route('/json')
def json():
    with open('json_file.json','r') as f:
        data = json.loads(f.read())
    f.close()
    return jsonify(data)

if __name__ == '__main__':
    # Run the app server on localhost:4449
    app.run('localhost', 4449)

And here's the json file :

    "error": [],
    "id": 6
}

My problem is that whenever I wanted to access localhost:4449/json I get an error statement. Here's what my terminal returns :

AttributeError: 'function' object has no attribute 'loads'

I think it means it doesn't recognize .loads as a function and I don't know why. I also get the same error with the json.load() function.

Do you have an idea why this happens ?

CodePudding user response:

Do not call that function json. You are also using module with that name. That would shadow outer definition of json.

  • Related