2017-04-13 48 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))將避免錯誤!