Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - JSON Load from file not working

So I am writing a basic multipurpose script which uses json to import a dictionary from a file but for some reason it doesn't save properly. I've looked all over and can't find anything relating to my exact problem.

Here is my code:

import json
dicti = json.loads(open('database.db'))
print(str(dicti))

But then I get this error:

TypeError: JSON object must be str, not TextIOWrapper.

So does anyone have any ideas on what the problem is? Thanks in Advance.

Note: Currently the file only has inside it:

{}
like image 688
Dan Alexander Avatar asked Sep 27 '14 06:09

Dan Alexander


People also ask

How do I read a JSON file and convert to string in Python?

Load the json file into a file object and read its contents with the file. read() function, which returns a string containing the file's contents. Use the json. loads() function to convert this string object into the required python dictionary and store the result in a variable jsonData.


1 Answers

You want json.load for loading a file. json.loads is for loading from a string.

like image 189
BrenBarn Avatar answered Sep 21 '22 16:09

BrenBarn