繁体   English   中英

将文件字符串数据转换为 json python

[英]Convert file string data to json python

我有文件,其中数据采用以下字符串格式。

Name      : XYZ
Address   : London
Occupation : Teacher 
Age       : 34

Name      : ABC
Address   : New York
Occupation : Business 
Age       : 39

我想将数据转换为 json,如下所示:

   {
    Name      : XYZ
    Address   : London
    Occupation : Teacher 
    Age       : 34
   },

   {
    Name      : ABC
    Address   : New York
    Occupation : Business 
    Age       : 39
   }

到目前为止,我已经尝试过以下方法:

def convert() :
    f = open("file.txt", "r")
    content = f.read()
    splitcontent = content.splitlines()
    data = json.dumps(splitcontent, default=lambda o: o.__dict__)
    print(data)

O/P: [Name      : XYZ,        Address   : London, Occupation : Teacher,  Age       : 34, Name      : ABC, Address   : New York, Occupation : Business, Age       : 39]
def convert(file_name):
    objects = []
    with open(file_name) as f:
        d = {}
        for line in f:
            if line.startswith("Age"):
                key, value = line.split(":")
                d[key.strip()] = value.strip()
                objects.append(d)
                d = {}
            else:
                try:
                    key, value = line.split(":")
                    d[key.strip()] = value.strip()
                except ValueError as v:
                    pass

    return objects
print(convert("infile.txt"))

暂无
暂无

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

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