[英]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文件時出錯。 而不是file.write(JsonResponse)
你應該使用json.dump(JsonResponse,file)
。 它會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.