【问题标题】:Cannot write dictionary to file in python using json.dumps()无法使用 json.dumps() 在 python 中将字典写入文件
【发布时间】:2017-12-31 06:53:05
【问题描述】:

我收到来自 JSON 转储的响应,我正在尝试将其加载到 log.txt 文件中,但这不会打印出任何内容

我的功能

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)

【问题讨论】:

  • Edit 你的问题并显示def self.send_request(...

标签: python json


【解决方案1】:

你需要使用的是dump()而不是dumps()

json.dump()

将 obj 序列化为 JSON 格式的流到 fp(支持 .write() 类文件对象

如果 ensure_ascii 为 False,则写入 fp 的某些块可能是 unicode 实例

json.dumps()

将 obj 序列化为 JSON 格式的 str

如果 ensure_ascii 为 False,则结果可能包含非 ASCII 字符 并且返回值可能是一个 unicode 实例

完整的细节可以在this线程上找到

【讨论】:

  • 嗨,它还是不行,我用过这个,io.open('log.txt', 'r+', encoding='utf-8') as f: # f.write (json.dumps(payload, ensure_ascii=False))
  • 如答案中所述,您需要使用转储而不是转储s。删除“s”:D
猜你喜欢
  • 2020-11-01
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-25
  • 2018-07-18
  • 2016-05-04
相关资源
最近更新 更多