Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read json file from python

Tags:

python

json

file

I am trying to read a json file from python script using the json module. After some googling I found the following code:

with open(json_folder+json) as json_file:
        json_data = json.loads(json_file)
        print(json_data)

Where json_folder+json are the path and the name of the json file. I am getting the following error:

str object has no attribute loads. 
like image 915
Jose Ramon Avatar asked Oct 03 '14 11:10

Jose Ramon


People also ask

How do I read a JSON file in Python?

Reading From JSON Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

How do I read a JSON file?

JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.


1 Answers

The code is using json as a variable name. It will shadow the module reference you imported. Use different name for the variable.

Beside that, the code is passing file object, while json.loads accept a string.

Pass a file content:

json_data = json.loads(json_file.read())

or use json.load which accepts file-like object.

json_data = json.load(json_file)
like image 134
falsetru Avatar answered Oct 13 '22 03:10

falsetru