1

下面是我的代码:

import requests

html = requests.get(

html_str = html.content
Html_file= open("fb_remodel.txt",'w')
Html_file.write(html_str)
Html_file.close()

这会产生一个文本文件

{"data":[{"id":"359434924192565_361115077357883","created_time":"2013-11-05T18:52:24+0000"},{"id":"116929191671920_664658976898936","created_time":"2013-11-05T18:51:57+0000"},

我希望在每个},.

4

3 回答 3

3

您可以使用 Python 的“json”模块“漂亮地打印”JSON

请参阅:http ://docs.python.org/2/library/json.html

漂亮的印刷:

import json
print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}
于 2013-11-05T19:20:30.207 回答
2

您收到一个没有任何换行符的 JSON 值;您必须自己手动插入换行符:

response = requests.get(...)
json_str = response.content
json_str = json_str.replace('},', '},\n')
with open('fb_remodel.txt', 'w') as json_file:
    json.file.write(json_str)

我在您的代码中将 'html' 替换为 'json' 并稍微改进了文件处理(在上面的代码中,with语句会为您自动关闭文件对象)。

该代码使用字符串替换将所有},字符串替换为},\n,有效地添加了原始响应没有的额外换行符。

于 2013-11-05T19:12:31.420 回答
1

使用 JSON 模块进行漂亮的打印:

import json
json_pp = json.dumps(html_str, sort_keys=True,
              indent=4, separators=(',', ': '))

Html_file= open("fb_remodel.txt",'w')
Html_file.write(json_pp)
Html_file.close()

我也会使用:

html_str = html.text

您可能知道,请求将使用正确的字符集将响应解码为 Unicode。

于 2013-11-05T19:17:52.397 回答