3 回答
TA贡献1772条经验 获得超6个赞
像这样解析每一行:
with open('input.json') as f:
for line in f:
obj = json.loads(line)
TA贡献1852条经验 获得超7个赞
因为您的文件不是有效的 JSON。您必须逐行读取文件,然后将每一行单独转换为对象。
或者,您可以像这样转换文件结构...
[
{
"value": 0.97,
"key_1": "value1",
"key_2": "value2",
"key_3": "value3",
"key_11": "2019-01-01T00:05:00Z"
},
{
"value": 0.97,
"key_1": "value1",
"key_2": "value2",
"key_3": "value3",
"key_11": "2019-01-01T00:05:00Z"
},
{
"value": 0.97,
"key_1": "value1",
"key_2": "value2",
"key_3": "value3",
"key_11": "2019-01-01T00:05:00Z"
}
]
它将是一个有效的 JSON 文件。
TA贡献1847条经验 获得超7个赞
正如 tanaydin 所说,您失败的输入不是有效的 json。它应该是这样的:
[
{
"value":0.97,
"key_1":"value1",
"key_2":"value2",
"key_3":"value3",
"key_11":"2019-01-01T00:05:00Z"
},
{"value":0.97,"key_1":"value1","key_2":"value2","key_3":"value3","key_11":"2019-01-01T00:05:00Z"},
{"value":0.97,"key_1":"value1","key_2":"value2","key_3":"value3","key_11":"2019-01-01T00:05:00Z"}
]
我假设您通过迭代对象列表并调用json.dumps每个对象来创建 json 输出。您应该创建字典列表,然后调用json.dumps整个列表。
list_of_dicts_to_jsonify = {}
object_attributes = ['value', 'key_1', 'key_2', 'key_3', 'key_11']
for item in list_of_objects:
# Convert object to dictionary
obj_dict = {}
for k in object_attributes:
obj_dict[k] = getattr(item, k) or None
list_of_dicts_to_jsonify.append(obj_dict)
json_output = json.dumps(list_of_dicts_to_jsonify)
添加回答
举报