2017-07-25 151 views
0

我越来越从JSON响应转储在Python文件,我试图将其加载到一个log.txt文件,但这并没有打印出任何东西无法写入字典使用json.dumps()

我的功能

def get_customer_last_action_executed(self): 
    """ 
    Get the customer last action executed 
    By inputing the CustomerID 
    :return: 
    """ 
    payload ={'customerID': self.CustomerID} 
    if not self.CustomerID: 
     customer_id = raw_input("Please provide the customer ID:") 
     self.CustomerID = customer_id 
     # raise Exception('No customerID provided') 

    response = self.send_request(self.get_customer_last_action_executed_url + self.CustomerID, 
           json.dumps(payload), 
           "GET") 

    print response.url, response.status_code 
    print response, response.text, response.reason 
    if response: 
     print self.sucessful_msg 
    else: 
     print self.error_msg 
    with open('log.txt', 'w') as f: 
     json.dumps(payload, f) 
+0

[编辑]你的问题并显示'def self.send_request(...'。 – stovfl

回答

2

你需要使用什么是dump()没有dumps()

传入json.dump()

序列化OBJ作为JSON格式流FP(一个.WRITE() - 支撑 类文件对象

如果ensure_ascii为False,一些块写入到FP可以是Unicode 实例

json.dumps()

序列化obj转换为JSON格式的STR

如果ensure_ascii是假,结果可能包含非ASCII字符 和返回值可以是unicode的实例

全部细节可以找到this线程

+0

嗨,它不仍然工作,我用这个,与io.open('log.txt','r +',encoding ='utf-8')作为f: #f.write(json.dumps(有效载荷,ensure_ascii = False)) – Patcho

+0

正如答案中所提到的,你需要使用dump而不是dump * s *。删除“s”:D – Nabin