[英]Convert file string data to json python
I've file where data is in below string format.我有文件,其中数据采用以下字符串格式。
Name : XYZ
Address : London
Occupation : Teacher
Age : 34
Name : ABC
Address : New York
Occupation : Business
Age : 39
I want to convert data to json as show in below format:我想将数据转换为 json,如下所示:
{
Name : XYZ
Address : London
Occupation : Teacher
Age : 34
},
{
Name : ABC
Address : New York
Occupation : Business
Age : 39
}
I've tried below so far:到目前为止,我已经尝试过以下方法:
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.