繁体   English   中英

在python中将文件中的对象转换为json

[英]Converting objects in file to json in python

我有一个包含多个对象的文件,如下所示:

{ 
    name: (sindey, crosby)
    game: "Hockey"
    type: athlete
},
{ 
    name: (wayne, gretzky)
    game: "Ice Hockey"
    type: athlete
}

...我想将它们转换为 JSON 格式并输出:

[
    { 
        "name": "(sindey, crosby)",
        "game": "Hockey",
        "type": "athlete"
    },
    { 
        "name": "(wayne, gretzky)",
        "game": "Ice Hockey",
        "type": "athlete"
    }
]

如果输入是这种格式,

 name: (sidney, crosby) | game:"Hockey" |  type:athlete 
 name: (wayne, gretzky) | game:"Ice Hockey" |  type:athlete

我可以使用带有 list 和 dict 的 json dump 来实现,它给了我想要的输出

import json

f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
for v in splitcontent:
    l = v.split(' | ')
    d.append(dict(s.split(':',1) for s in l))


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

如何重新格式化此代码以将输入转换为 JSON 格式?

像这样的东西可能适用于大多数情况 - 您只需将带有花括号的行与带有数据的行分开处理:

import json

f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
appendage = {}
for line in splitcontent:
    if ('}' in line) or ('{' in line):
        # Append a just-created record and start a new one
        if appendage:
            d.append(appendage)
        appendage ={}
    else:
        key, val = line.split(':',1)
        if val.endswith(','):
            # strip a trailing comma
            val = val[:-1]
        appendage[key] = val


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys= False)))

我可能也有一些错别字...

@sarah Messer 给出的答案略有变化。 涉及的变化

没有 : 分隔符的行被跳过

尝试这个

import json


f = open("log.file", "r")
content = f.read()
splitcontent = content.splitlines()

d = []
appendage = {}
for line in splitcontent:

    if ('}' in line) or ('{' in line) or ('{' in line) or ('}' in line):
        # Append a just-created record and start a new one
        if appendage:
            d.append(appendage)
            appendage = {}
        continue

    key, val = line.split(':')

    if val.endswith(','):
        # strip a trailing comma
        val = val[:-1]
        print(val)
    # if val == "":
    #     pass
    # else:
    appendage[key] = val


with open("json_log.json", 'w') as file:
    file.write((json.dumps(d, indent=4, sort_keys=False)))

暂无
暂无

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

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