Python:转储到Json添加额外的双引号和转义引号

时间:2014-08-11 11:31:25

标签: python json

我正在使用python工具检索Twitter数据,并将它们以JSon格式转储到我的磁盘中。我注意到用双引号括起来的推文的整个数据字符串的意外转义。此外,实际Json格式的所有双引号都使用反斜杠进行转义。

他们看起来像这样:

  

“{\”created_at \“:\”Fri Aug 08 11:04:40 +0000   2014 \”,\ “ID \”:497699913925292032,

我该如何避免?它应该是:

  

{“created_at”:“Fri Aug 08 11:04:40 +0000 2014”.....

我的文件输出代码如下所示:

with io.open('data'+self.timestamp+'.txt', 'a', encoding='utf-8') as f:
            f.write(unicode(json.dumps(data, ensure_ascii=False)))
            f.write(unicode('\n'))

意外转义会导致在稍后的处理步骤中读取json文件时出现问题。

4 个答案:

答案 0 :(得分:90)

您正在对JSON字符串进行双重编码。 data 已经一个JSON字符串,并且不需要再次编码

>>> import json
>>> not_encoded = {"created_at":"Fri Aug 08 11:04:40 +0000 2014"}
>>> encoded_data = json.dumps(not_encoded)
>>> print encoded_data
{"created_at": "Fri Aug 08 11:04:40 +0000 2014"}
>>> double_encode = json.dumps(encoded_data)
>>> print double_encode
"{\"created_at\": \"Fri Aug 08 11:04:40 +0000 2014\"}"

只需将这些内容直接写入您的文件:

with open('data{}.txt'.format(self.timestamp), 'a') as f:
    f.write(data + '\n')

答案 1 :(得分:0)

发生这种不必要的转义的另一种情况是,如果您尝试在json.dumps()的预处理输出上使用json.dump()。例如

import json, sys
json.dump({"foo": json.dumps([{"bar": 1}, {"baz": 2}])},sys.stdout)

将导致

{"foo": "[{\"bar\": 1}, {\"baz\": 2}]"}

为避免这种情况,您需要传递字典,而不是传递json.dumps()的输出,例如

json.dump({"foo": [{"bar": 1}, {"baz": 2}]},sys.stdout)

输出所需的

{"foo": [{"bar": 1}, {"baz": 2}]}

(为什么要用json.dumps()预处理内部列表?恩,我有另一个函数正在用其他东西创建内部列表,所以我认为返回一个该功能的json对象...错了。)

答案 2 :(得分:0)

扩展到其他有类似问题的人,我用它来将 JSON 格式的数据转储到数据来自 API 调用的文件中。下面只是一个指示性示例,根据您的要求进行更新

import json

# below is an example, this came for me from an API call
json_string = '{"address":{"city":"NY", "country":"USA"}}'

# dump the JSON data into file ( dont use json.dump as explained in other answers )
with open('direct_json.json','w') as direct_json:    
    direct_json.write(json_string)
    direct_json.write("\n")

# load as dict
json_dict = json.loads(json_string)

# pretty print
print(json.dumps(json_dict, indent = 1)) 

# write pretty JSON to file
with open('formatted.json','w') as formatted_file: 
    json.dump(json_dict, formatted_file, indent=4)  

答案 3 :(得分:0)

解决这个问题的简单方法是在转储之前使用 json 加载函数,如下所示:

import json
data = json.loads('{"foo": json.dumps([{"bar": 1}, {"baz": 2}])}')
with open('output.json','w') as f:
   json.dump(data,f,indent=4)