我正在尝试使用自定义的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)有人能帮我解决这个问题吗。
谢谢!
发布于 2017-04-13 17:31:40
首先,摆脱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))发布于 2017-04-13 17:52:09
错误是在写入JSON文件时发生的。而不是file.write(JsonResponse),您应该使用json.dump(JsonResponse,file)。看起来不错。
https://stackoverflow.com/questions/43397675
复制相似问题