Python 如何从web查询保存json内容
以下代码用于查询和保存json响应。查询返回一个json输出,但是当我用代码保存它时,我就不能再保留json格式了Python 如何从web查询保存json内容,python,json,web,urllib2,Python,Json,Web,Urllib2,以下代码用于查询和保存json响应。查询返回一个json输出,但是当我用代码保存它时,我就不能再保留json格式了 file_out='C:\\Users\\ayush488\\Desktop\\annotation_for_new_dataset\\url'+str(cnt)+'.txt' cnt=cnt+1 response=urllib2.urlopen('http://www.diffbot.com/api/article?token='+token+'&url
file_out='C:\\Users\\ayush488\\Desktop\\annotation_for_new_dataset\\url'+str(cnt)+'.txt'
cnt=cnt+1
response=urllib2.urlopen('http://www.diffbot.com/api/article?token='+token+'&url='+url).read()
with open(file_out,'w') as outfile:
json.dump(response,outfile)
有人知道如何正确保存json内容吗
以下是输出的示例:
"{\"icon\":\"http:\\/\\/open.blogs.nytimes.com\\/favicon.ico\",\"author\":
您正在对JSON响应进行双重编码 您将收到一个字符串值,
json.loads()
可以将其转换为Python对象。要将响应保存到文件中,不要编码,不要解码,只需将其直接保存到文件对象。最有效的方法是使用:
您正在对JSON响应进行双重编码 您将收到一个字符串值,
json.loads()
可以将其转换为Python对象。要将响应保存到文件中,不要编码,不要解码,只需将其直接保存到文件对象。最有效的方法是使用:
outfile.write(response)
outfile.write(response)
为什么copyfileobj比outfile.write(response)更高效?因为如果响应大,它会以块的形式流式传输响应。为什么copyfileobj比outfile.write(response)更高效?因为如果响应大,它会以块的形式流式传输响应。
import shutil
response=urllib2.urlopen('http://www.diffbot.com/api/article?token='+token+'&url='+url).read()
with open(file_out,'w') as outfile:
shutil.copyfileobj(response, outfile)