Json Error while reading a nested list from a file

Question:

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?

Asked By: user17302

||

Answers:

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

Edit: a solution that will give you a nested list manually

import ast

def main():
    with open('input.txt') as f: # input.txt contains: [[i,1],[i,2]]
        input = f.read() # read file content as one big string
    print(input)        # [[i,1],[i,2]]
    print(type(input))  # <class 'str'>


    res = input.replace("i", ""i"") # replace plain i with an i with double quotes
    print(res) # [["i",1],["i",2]]
    literal_result = ast.literal_eval(res)
    print(literal_result) # [['i', 1], ['i', 2]] 
    print(type(literal_result)) # <class 'list'>

if __name__ == "__main__":
    main()
Answered By: Shushiro

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: “[[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 as a key-value pair (for demonstrating purposes) like this: “{“sample_key: “[[i,1],[i,2]]”}”, it will work.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.