2017-04-13 58 views
1

我试图用我的自定义json输入创建新的json文件并将JSON转换为HTML格式并保存到.html文件中。但是在生成JSON和HTML文件时出现错误。请找到我的下面的代码 - 不知道我在做什么错在这里:json2html python lib不工作

#!/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) 

有人可以帮我解决这个问题。

谢谢!

回答

0

首先,摆脱您的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)) 
+0

非常感谢!它的工作 –

0

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

+0

非常感谢!感谢你的帮助 –