I saved a list with dict entries to a txt file.
When I try to read it back into python with
JavaScript
x
2
1
data = open("my_saved_data.txt","r")
2
I just get a huge string which looks like this:
JavaScript
1
2
1
[{key1:"value",key2:"value"},{key1:"value",key2:"value"},{key1:"value",key2:"value"}]
2
What’s an easy way to get this back in the original format?
Advertisement
Answer
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:
JavaScript
1
2
1
[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]
2
then we can convert it to original format:
JavaScript
1
12
12
1
with open("my_saved_data.txt","r") as f:
2
data = f.read()
3
4
print(data)
5
# '[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}]'
6
7
import json
8
json.loads(data)
9
#[{'key1': 'value', 'key2': 'value'},
10
# {'key1': 'value', 'key2': 'value'},
11
# {'key1': 'value', 'key2': 'value'}]
12
Please make sure whether your key in str is enclosed or not, if not, we can make it enclosed by:
JavaScript
1
5
1
with open("my_saved_data.txt","r") as f:
2
data = f.read()
3
4
data.replace('key1','"key1"').replace('key2','"key2"')
5