2 回答
TA贡献1802条经验 获得超5个赞
您将无法使用json. 您必须先替换所有单引号,然后使用json.loads. 但是,您也可以使用ast以读取单引号 json,如下所示:
import ast
from io import StringIO
data = """
{'user': 'fgb59h', 'stars': 4.0, 'time': 1027296000}
{'user': 'bucho_ky', 'stars': 2.0, 'time': 1201305600}
{'user': 'redp944', 'stars': 4.0, 'time': 1118016000}
"""
records = list()
for line in StringIO(data).readlines():
if not len(line.strip()): continue
data_dict = ast.literal_eval(line)
records.append(data_dict)
print(records)
哪个输出:
[{'stars': 4.0, 'time': 1027296000, 'user': 'fgb59h'},
{'stars': 2.0, 'time': 1201305600, 'user': 'bucho_ky'},
{'stars': 4.0, 'time': 1118016000, 'user': 'redp944'}]
TA贡献1825条经验 获得超6个赞
您可以阅读每一行,附加到一个列表,以后可以使用ast:
提交Json.json:
{'user': 'fgb59h', 'stars': 4.0, 'time': 1027296000}
{'user': 'bucho_ky', 'stars': 2.0, 'time': 1201305600}
{'user': 'redp944', 'stars': 4.0, 'time': 1118016000}
因此:
import json
import ast
res = []
with open('commitJson.json', 'r') as fp:
for line in fp:
res.append(line.strip())
print(json.dumps([ast.literal_eval(i) for i in res], indent = 4))
输出:
[
{
"user": "fgb59h",
"stars": 4.0,
"time": 1027296000
},
{
"user": "bucho_ky",
"stars": 2.0,
"time": 1201305600
},
{
"user": "redp944",
"stars": 4.0,
"time": 1118016000
}
]
短版:
with open('commitJson.json', 'r') as fp:
print(json.dumps([ast.literal_eval(line.strip()) for line in fp], indent = 4))
添加回答
举报