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

Time:01-23

I saved a list with dict entries to a txt file.

When I try to read it back into python with

data = open("my_saved_data.txt","r")

I just get a huge string which looks like this:

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

What's an easy way to get this back in the original format?

CodePudding user response:

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"')

CodePudding user response:

use JSON library read file decode json create object

import json
json_string = open("my_saved_data.txt","r").read()
data= json.loads(json_string)
  •  Tags:  
  • Related