如果字符串类似于 json 但包含"?



我想让它成为一个列表对象,但是' inSample的Rd使它变得非常困难。

我试着:

json.load()、split()、strip()和ast.literal_eval()

[{'long_name': 'Sample's Road', 'short_name': 'Sample's Rd', 'types': ['route']}, {'long_name': 'England', 'short_name': 'England', 'types': ['boo', 'far']}]

我需要一个解决方案,我也可以使用其他实例没有'在名称中,有不同数量的键值对。

我可以给你一个解决方案:问题是""在字典中解析的键中。我们必须去掉它,所以我们把list作为字符串,去掉""然后把它做成JSON。

import ast
import re
#list_string = "<your_list>"
list_string = "[{'long_name': 'Sample's Road', 'short_name': 'Sample's Rd', 
'types': 
['route']}, {'long_name': 'England', 'short_name': 'England', 'types': 
['boo', 'far']}]"
# remove the extra "`" between words for specific word
# - > list_string = list_string.replace("e's", "e s")
#remove the extra "`" between words for all words
new_string = re.sub('{[^a-zA-Z0-9n.]}:', '', list_string)
# now your problem has been solved, turn the string to list and dump it
final_list = ast.literal_eval(new_string)
json.dumps(final_list)

最新更新