2017-04-13 51 views
0

我使用python脚本创建两个文件,第一个文件是JSON,第二个是HTML文件,我的下面是创建json文件,但创建HTML文件时出现错误。有人可以帮我解决这个问题吗?我是新来的Python脚本,因此将非常感激,如果你能提出一些解决方案在python中创建多个文件时获取错误

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

import sys 
import json 


JsonResponse = '[{"status": "active", "due_date": null, "group": "later", "task_id": 73286}]' 


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) 
      print infoFromJson 
      htmlReportFile = 'Report.html' 
      htmlfile = open(htmlReportFile, 'w') 
      htmlfile.write(infoFromJson) 
      htmlfile.close() 
    except: 
     print 'error occured' 
     sys.exit(0) 


create(JsonResponse) 

我用下面的在线Python编辑器来执行我的代码:

https://www.tutorialspoint.com/execute_python_online.php

+0

在某些地方使用'open'而不是别人是......不可思议的。 – tripleee

回答

0
infoFromJson = json.load(json_data) 

这里,json.load()将期望有效的json数据为json_data。但你提供的json_data是无效的json,它是一个简单的字符串(Hello World!)。所以,你得到的错误。

ValueError: No JSON object could be decoded

更新:

在你的代码应该得到的错误:

TypeError: expected a character buffer object

那是因为,你正在写的文件中的内容必须是字符串,但它取代,你有一本字典清单。

解决这个问题的两种方法。将行:

htmlfile.write(infoFromJson) 

要么此:

htmlfile.write(str(infoFromJson)) 

为了infoFromJson的字符串。

或者使用dump实用json模块:

json.dump(infoFromJson, json_data) 
+0

感谢您的回复。我现在给了一个正确的json - 我已经在我的消息中用有效的json更新了我的帖子,但仍然得到了同样的错误。 –

+0

查看已更新的答案。 –

0

如果删除Try...except语句,你会看到下面的错误:

Traceback (most recent call last): File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 26, in <module> create(JsonResponse) File "/Volumes/Ithink/wechatProjects/django_wx_joyme/app/test.py", line 22, in create htmlfile.write(infoFromJson) TypeError: expected a string or other character buffer object

发生了错误,因为htmlfile.write需要string type,但infoFromJson是一个列表。
因此,将htmlfile.write(infoFromJson)更改为htmlfile.write(str(infoFromJson))将避免错误!