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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With