首页 > 解决方案 > 解析json转储文件时python中的关键错误

问题描述

我正在尝试通过使用失败表访问 JSON 文件来添加表。执行此代码时,我得到 keyerror。

if hasattr(result.table, 'key_column'): KeyError: 'key_column'

没有 key_column 属性。但是为什么代码会进入 if 条件?

import json


with open(report_file_name, 'r') as json_file:
        data = json.load(json_file, object_hook=AttributeDictionary)
failure_table_name = add_table(table_style, args.test_id, results_directory, data.failure_table)

import os.path
import dominate


def add_table(table_style, test_id, results_directory, result):
    if hasattr(result.table, 'key_column'):
        result.table.data = sorted(result.table.data, key=lambda x: x[result.table.key_column])
    doc = dominate.document(title=result.name)
    doc.body.add(style(table_style, type='text/css'))
    doc.body.add(p(result.title, _class='table_title'))
    result_table = doc.body.add(table(_class='report_table'))
    table_body = result_table.add(tbody())
    table_row = table_body.add(tr())
    for entry in result.table.header:
        table_row.add(th(entry))
    for row, table_class in zip(result.table.data, get_table_class_iter()):
        table_row = table_body.add(tr())
        for entry in row:
            table_row.add(td(entry, _class=table_class))
    file_name = "%s_%s.htm" % (test_id, result.name)
    file_path = os.path.join(results_directory, file_name)
    with open(file_path, 'w') as html_file:
        html_file.write(str(doc))
    return file_name

   "failure_table": {
        "table": {
            "header": [
                "Level",
                "Category",
                "Title",
                "Device Name",
                "Timestamp"
            ],
            "data": [
                [
                    "Failure",
                    "Stability",
                    "Critical thread \"PSAV\" not found",
                    "Gateway01",
                    "2019-07-19 07:05:42.422788"
                ],
                [
                    "Failure",
                    "Stability",
                    "Critical thread \"PSAV\" not found",
                    "Gateway01",
                    "2019-07-19 07:06:04.848708"
                ]
            ]
        },
        "type": "table",
        "name": "failure_table",
        "title": "Failure Table"

标签: pythonjson

解决方案


推荐阅读