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