Following this post, I used the following code:
with open(mytextFile) as f:
nestedList = json.load(f)
print(nestedList)
my textfile consists of [[i,1],[i,2]]
only. When I run the above code, I get the error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 3 (char 2)
I have tried both with adding and removing the option encoding='utf-8', also with files with other extensions than txt. The same error occurs all the time.
Could you help please?
Edit: If this is not the right way to read nested lists from a file, could you point me to the right direction?
CodePudding user response:
When checking the input with https://jsonformatter.curiousconcept.com/ it hints on the issue. The keys (i in your input) are not quoted. If you quote them in the input, the file contents can be parsed with your implementation (exemplary input would be [["i",1],["i",2]], having the keys in quotes).
Maybe the solutions provided here help you: Bad JSON - Keys are not quoted
CodePudding user response:
If you can provide the contents of the text file that you are using, it would be better.
However I am assuming that the contents of the file is a plain string which is “[[i,1],[i,2]]”.
However, json.load() converts a JSON formatted string (not any arbitrary string), to a Python dictionary. In your case, the contents of the string is “[[i,1],[i,2]]” which is not in a JSON format. A JSON document is always an object itself.
If you rewrite the same in a key value pair (for demonstrating purposes) like this: “{“sample_key: “[[i,1],[i,2]]”}”, it will work.