json2html python 库不工作

json2html python lib is not working

我正在尝试使用我的自定义 json 输入创建新的 json 文件,并将 JSON 转换为 HTML 格式并保存为 .html文件。但是我在生成 JSON 和 HTML 文件时遇到错误。请找到我的以下代码 - 不确定我在这里做错了什么:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from json2html import *
import sys
import json

JsonResponse = {
        "name": "json2html",
        "description": "Converts JSON to HTML tabular representation"
}

def create(JsonResponse):
    #print JsonResponse
    print 'creating new  file'
    try:
        jsonFile = 'testFile.json'
        file = open(jsonFile, 'w')
        file.write(JsonResponse)
        file.close()
        with open('testFile.json') as json_data:
            infoFromJson = json.load(json_data)
            scanOutput = json2html.convert(json=infoFromJson)
            print scanOutput
            htmlReportFile = 'Report.html'
            htmlfile = open(htmlReportFile, 'w')
            htmlfile.write(str(scanOutput))
            htmlfile.close()
    except:
        print 'error occured'
        sys.exit(0)


create(JsonResponse)

谁能帮我解决这个问题。

谢谢!

首先,摆脱你的 try / except。在没有类型表达式的情况下使用 except 几乎总是一个坏主意。在这种特殊情况下,它使您无法知道到底出了什么问题。

在我们删除裸 except: 后,我们得到这个有用的错误消息:

Traceback (most recent call last):
  File "x.py", line 31, in <module>
    create(JsonResponse)
  File "x.py", line 18, in create
    file.write(JsonResponse)
TypeError: expected a character buffer object

果然JsonResponse不是字符串(str),而是字典。这很容易修复:

    file.write(json.dumps(JsonResponse))

这是一个 create() 子程序,其中包含我推荐的其他一些修复程序。请注意,写转储 JSON 后立即加载 JSON 通常是愚蠢的。我假设您的实际程序做了一些稍微不同的事情。

def create(JsonResponse):
    jsonFile = 'testFile.json'
    with open(jsonFile, 'w') as json_data:
        json.dump(JsonResponse, json_data)
    with open('testFile.json') as json_data:
        infoFromJson = json.load(json_data)
        scanOutput = json2html.convert(json=infoFromJson)
        htmlReportFile = 'Report.html'
        with open(htmlReportFile, 'w') as htmlfile:
            htmlfile.write(str(scanOutput))

写入 JSON 文件时出错。您应该使用 json.dump(JsonResponse,file) 而不是 file.write(JsonResponse)。它会起作用。