-1

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?

Karl 17302
  • 57
  • 6

2 Answers2

2

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()
Shushiro
  • 577
  • 1
  • 9
  • 32
  • The exact contents of my file, after adding qoutes is: [['i1',1],['i2',2]] – Karl 17302 Dec 19 '22 at 10:24
  • do you have control over the input files (or their generation). In that case it might be the simplest solution if you adjust so that the keys are always quoted. If you do not have control and the input file's structure is too much to edit manually, the json package won't get you far as pointed out by @Tirthya 's answer. I will see to get an example with dmejson or hjson working asap – Shushiro Dec 19 '22 at 10:43
  • Thanks for the reply. I have added both single and double qoutes to the keys and I still get the same error. I will try to talk to the provider of the libarary to see if they agree to change the output file, but not sure. Would you suggest a specific library that might be useful here? Or simply reading all the file at once and parsing the string based on certain characters? – Karl 17302 Dec 19 '22 at 15:17
  • Hm, it is strange that your exemplary input with quotes does not work for you. I think the simplest solution would be to recieve valid JSON and use the json package. If you cannot change the input you get, I think you have to parse it manually. Could you edit your question to include the desired output? When you have read the nested lists, what structure should come out at runtime? A nested list again or a list of sets, a list of dictionaries? It would be simpler to provide a solution for you then – Shushiro Dec 20 '22 at 07:42
  • 1
    I have edited my answer so it might do what you need/want. It includes debug output you might not need (all the print statements) – Shushiro Dec 20 '22 at 08:14
  • Thank you for editing your answer and providing the code. Great!!!!!! – Karl 17302 Dec 21 '22 at 08:03
-1

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.

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • If this is not the right way to read nested lists from a file, could you point me to the right direction? – Karl 17302 Dec 19 '22 at 10:26
  • The exact contents of my file, after adding qoutes is: [['i1',1],['i2',2]] – Karl 17302 Dec 19 '22 at 10:26
  • 1
    [["i1",1],["i2",2]] is valid JSON. Note the use of double-quotes – DarkKnight Dec 19 '22 at 11:58
  • There are several things wrong here. `json.load()` does not just load dictionaries (i.e. JSON objects) but can load any JSON type, including lists, as the top-level value. "A JSON document is always an object itself." is similarly wrong as *any* JSON type can be the top-level value in JSON. The proposed solution of using `“{“sample_key: “[[i,1],[i,2]]”}”` as *input* has several syntax errors (the quoting violates both JSON and Python syntax), the outer object is redundant (as mentioned before) and the value `“[[i,1],[i,2]]”` would be loaded as a *string* instead of the desired list. – MisterMiyagi Dec 20 '22 at 06:23