简体   繁体   中英

How to write multiple dictionaries into json/txt file and read them back?

I need to write multiple dict into json and then read them back. How can I do that? The code I use write the dictionaries to file but i am not able to read them.

if "__main__" == __name__:
    s = 0
    if s == 0:
        for i in range(2):
            test = dict()
            test["test_1"] = i
            test["test_2"] = i+1
            f = open('test.txt', 'a')
            f.write(json.dumps(test))
    else:
        f = open('test.txt', 'r')
        test = json.loads(f.read())
        print(test)

Error while reading:

test = json.loads(f.read())
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 27 (char 26)

You can't have multiple dictionaries (or multiple objects) in a json file. But you can have a list:

if "__main__" == __name__:
    s = 0
    if s == 0:
        arr = []
        for i in range(2):
            test = dict()
            test["test_1"] = i
            test["test_2"] = i+1
            arr.append(test)
        with open('test.json') as f:
            json.dump(arr, f)
    else:
        with open('test.json') as json_file:
            test = json.load(json_file)
        test_0 = test[0]
        test_1 = test[1]
        print(test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM