Zel*_*ian 85 python twitter json pretty-print
类的项目涉及解析Twitter JSON数据.我正在获取数据并将其设置到文件中没有太多麻烦,但它只是一行.这对我正在尝试的数据操作很好,但是文件非常难以阅读,我无法很好地检查它,使得为数据操作部分编写代码非常困难.
有没有人知道如何从Python中做到这一点(即不使用命令行工具,我无法工作)?到目前为止,这是我的代码:
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
twitterDataFile = open("twitterData.json", "wb")
# magic happens here to make it pretty-printed
twitterDataFile.write(output)
twitterDataFile.close()
Run Code Online (Sandbox Code Playgroud)
注意我很感激有人指着我简单的文档等等,但正如我所说,我已经看过并继续需要帮助.一个真正有用的回复将比那里的例子更详细和更具说明性.谢谢
另外: 在Windows命令行中尝试此操作:
more twitterData.json | python -mjson.tool > twitterData-pretty.json
Run Code Online (Sandbox Code Playgroud)
结果如下:
Invalid control character at: line 1 column 65535 (char 65535)
Run Code Online (Sandbox Code Playgroud)
我会给你我正在使用的数据,但它非常大,你已经看到了我用来制作文件的代码.
mat*_*ski 79
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()
Run Code Online (Sandbox Code Playgroud)
dka*_*ins 64
你可以解析JSON,然后用这样的缩进再次输出它:
import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅http://docs.python.org/library/json.html.
小智 47
import json
with open("twitterdata.json", "w") as twitter_data_file:
json.dump(output, twitter_data_file, indent=4, sort_keys=True)
Run Code Online (Sandbox Code Playgroud)
你并不需要json.dumps(),如果你不想以后解析字符串,只需简单地使用json.dump().它也更快.
Ran*_*Rag 14
您可以使用python的json模块进行打印.
>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
"4": 5,
"6": 7
}
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下
>>> print json.dumps(json_output, indent=4)
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您正在生成新的 *.json 或修改现有的 josn 文件,请使用“缩进”参数来获得漂亮的 json 格式。
import json
responseData = json.loads(output)
with open('twitterData.json','w') as twitterDataFile:
json.dump(responseData, twitterDataFile, indent=4)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
81682 次 |
| 最近记录: |