How to get a list with dict entries from text file?

Solution 1:

What you want is "Convert a String to JSON", but the type of your file content is not JSON, because the key in JSON should be enclosed in double quotes.

The correct content should like this:

[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]

then we can convert it to original format:

with open("my_saved_data.txt","r") as f:
    data = f.read()

print(data)
# '[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]'

import json
json.loads(data)
#[{'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'},
# {'key1': 'value', 'key2': 'value'}]

Please make sure whether your key in str is enclosed or not, if not, we can make it enclosed by:

with open("my_saved_data.txt","r") as f:
    data = f.read()

data.replace('key1','"key1"').replace('key2','"key2"')