无法使用json.dumps()在python中写字典到文件

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

我从一个JSON转储中得到了一个响应,我正试图将它加载到一个log.txt文件中,但这不会打印出任何内容。

我的职能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)


您需要使用的是dump(),而不是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

在这个线程上可以找到完整的详细信息