简体   繁体   English

Python 模块,用于处理和清理类 json 文件

[英]Python module to process and clean json-like files

I received a file which contains key and unquoted values which looks like a json file but is not valid due to unquoted keys and values.我收到了一个包含键和未引用值的文件,该文件看起来像 json 文件,但由于未引用的键和值而无效。

Is there an existing module in python that will be able to load this and clean it as a valid json file? python 中是否有一个现有模块能够加载并清理它作为有效的 json 文件?

sample.txt样本.txt

{
 apple: [green,red],
 kiwi: [green,gold],
 strawberry: red
}

Solution is described on How to turn a string with unquoted keys into a dict in Python How to turn a string with unquoted keys into a dict in Python

In your case code should be:在您的情况下,代码应该是:

class identdict(dict):
    def __missing__(self, key):
        return key

dict_file = open('sample.txt')

uq_dict = dict_file.read()
real_dict = eval(uq_dict, identdict())

print(real_dict)
print(real_dict['kiwi'][1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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