我有在python中將此輸入轉換為json格式的代碼:
{
name: (sidney, crosby)
game: "Hockey"
type: athlete
},
{
name: (wayne, gretzky)
game: "Ice Hockey"
type: athlete
}
代碼:
import json
import os
user_input = input("Enter the path of your file: ")
assert os.path.exists(user_input), "Invalid file at, " str(user_input)
f = open(user_input, 'r')
content = f.read()
def parse_records(txt):
reclines = []
for line in txt.split('\n'):
if ':' not in line:
if reclines:
yield reclines
reclines = []
else:
reclines.append(line)
def parse_fields(reclines):
res = {}
for line in reclines:
key, val = line.strip().rstrip(',').split(':', 1)
res[key.strip()] = val.strip()
return res
res = []
for rec in parse_records(content):
res.append(parse_fields(rec))
print(json.dumps(res, indent=4))
輸出:
[
{
"name": "(sidney, crosby)",
"game": "\"Hockey\"",
"type": "athlete"
},
{
"name": "(wayne, gretzky)",
"game": "\"Ice Hockey\"",
"type": "athlete"
}
]
我想輸出名稱的特定 json 值,即:
(sidney, crosby), athlete
(wayne, gretzky), athlete
我添加了這些行
res = []
for rec in parse_records(content):
res.append(parse_fields(rec))
my_json = json.load(res)
for data in my_json:
print(data["name"], data["type"])
但我得到了錯誤:
Traceback (most recent call last):
File "C:\Users\670274890\PycharmProjects\Proj\main.py", line 30, in <module>
my_json = json.load(res)
File "C:\Users\670274890\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'
我是否需要存盤轉換后的 json 檔案,然后對其進行決議以輸出特定值,或者有沒有辦法修復我寫的最后幾行以獲得所需的輸出?
uj5u.com熱心網友回復:
json一旦你有了你的res清單,你就不需要了。您只需遍歷該串列,列印您需要的內容:
for person in res:
print(person["name"], person["type"])
如果您需要保存res到檔案,那么json格式似乎是合理的。你應該在你的程式結束時有這個:
with open('output.json', 'w') as file:
json.dumps(res, file, indent=4)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/487363.html
