在Python中输出转换后的JSON值



我有代码将此输入转换为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:Users670274890PycharmProjectsProjmain.py", line 30, in <module>
my_json = json.load(res)
File "C:Users670274890AppDataLocalProgramsPythonPython39libjson__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'

我是否需要存储转换后的json文件,然后解析它以输出特定的值,或者是否有一种方法来修复我写的最后几行以获得所需的输出?

一旦有了res列表,就不需要json了。您只需遍历该列表,打印出您需要的内容:

for person in res:
print(person["name"], person["type"])

如果您需要将res保存到文件中,那么json格式似乎是合理的。你应该在你的程序末尾有这个:

with open('output.json', 'w') as file:
json.dumps(res, file, indent=4)

最新更新