簡體   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