【问题标题】:How to clean up my JSON response before writing to file in python/django?如何在写入 python/django 文件之前清理我的 JSON 响应?
【发布时间】:2016-12-23 19:36:02
【问题描述】:

这是函数将字典转换为 json 的 HttpResponse -

HttpResponse(
    json.dumps(cm_dict),
    content_type='application/javascript; charset=utf8'
)

我了解到,由于设置了内容类型,因此 json 响应显示得很漂亮。但我想要做的是将 json 写入文件并采用某种类似的格式。

我得到的是这个——

"{\"a\" : \"b\", \"c\" : \"d\"}"

使用以下内容写入文件 -

with open('data.json', 'w') as outfile:
    json.dump(json_data, outfile, sort_keys=True, indent=4,ensure_ascii=False)

我想要的是——

{
  "a": "b",
  "c": "d"
}

【问题讨论】:

    标签: json django python-2.7


    【解决方案1】:

    看起来json_data 的内容已经是 JSON。无需再次转储到 JSON;只写字符串。

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 1970-01-01
      • 2015-10-21
      • 2020-09-02
      • 1970-01-01
      • 2013-04-05
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多