简体   繁体   中英

Cannot write dictionary to file in python using json.dumps()

I'm getting a response from a JSON dumps, and I'm trying to load it in a log.txt file, but this doesn't print out anything

My Function

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)

What you need to use is dump() not dumps() .

json.dump()

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object

If ensure_ascii is False, some chunks written to fp may be unicode instances

json.dumps()

Serialize obj to a JSON formatted str

If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance

Full details can be found on this thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM