使用Python 3,我从URL请求json文档.
response = urllib.request.urlopen(request)
Run Code Online (Sandbox Code Playgroud)
该response对象是一个类似文件的对象read和readline方法.通常,可以使用以文本模式打开的文件创建JSON对象.
obj = json.load(fp)
Run Code Online (Sandbox Code Playgroud)
我想做的是:
obj = json.load(response)
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为urlopen以二进制模式返回文件对象.
当然,解决方法是:
str_response = response.read().decode('utf-8')
obj = json.loads(str_response)
Run Code Online (Sandbox Code Playgroud)
但这感觉很糟糕......
有没有更好的方法可以将字节文件对象转换为字符串文件对象?或者我错过任何参数urlopen或json.load给出编码?
我正在构建一个Web服务,并且有一个接受POST的节点来创建新资源.资源需要两种内容类型之一 - 我将定义的XML格式或表单编码变量.
这个想法是消费应用程序可以直接POST XML并从更好的验证等方面受益,但是还有一个HTML接口将POST表单编码的东西.显然XML格式有一个charset声明,但我看不到如何通过查看POST来检测表单的charset.
Firefox中表单的典型帖子如下所示:
POST /path HTTP/1.1
Host: www.myhostname.com
User-Agent: Mozilla/5.0 [...etc...]
Accept: text/html,application/xhtml+xml, [...etc...]
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 41
field1=value1&field2=value2&field3=value3
Run Code Online (Sandbox Code Playgroud)
这似乎不包含任何有用的字符集指示.
从我所看到的,application/x-www-form-urlencoded类型完全在HTML中定义,它只是列出了%-encoding规则,但没有说明数据应该在什么字符集中.
基本上,如果我不知道HTML最初呈现的字符集,有没有办法告诉字符集?否则,我将不得不尝试根据字符存在来猜测字符集,而且总是有点不确定.
在我的网络应用程序中,我使用jQuery的$.getJSON()方法提交了一些表单字段.我在编码方面遇到了一些问题.我的应用程序的字符集是charset=ISO-8859-1,但我认为这些字段是提交的UTF-8.
如何设置$.getJSON调用中使用的编码?
我有这串 Traor\u0102\u0160
Traor\u0102\u0160应该产生Traoré。然后Traoréutf-8解码应该产生Traorè
我如何将其转换为Traorè?
什么样的字符是Traor\u0102\u0160?Unicode?
我已经阅读了很多http://docs.python.org/howto/unicode.html#encodings。但是我还是很困惑。
我通过以下请求获取此数据:
import json
import requests
# making a request to get this json
r = requests.get('http://cdn.content.easports.com/fifa/fltOnlineAssets/2013/fut/items/web/199074.json')
print r.json
Run Code Online (Sandbox Code Playgroud)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests
headers = {'Content-Type': 'application/json'}
r = requests.get('http://cdn.content.easports.com/fifa/fltOnlineAssets/2013/fut/items/web/199074.json', headers=headers)
print r.content
#prints
{"Item":{"FirstName":"Lacina","LastName":"Traoré","CommonName":null,"Height":"203","DateOfBirth":{"Year":"1990","Month":"8","Day":"20"},"PreferredFoot":"Left","ClubId":"100766","LeagueId":"67","NationId":"108","Rating":"78","Attribute1":"79","Attribute2":"71","Attribute3":"45","Attribute4":"69","Attribute5":"50","Attribute6":"72","Rare":"1","ItemType":"PlayerA"}}
Run Code Online (Sandbox Code Playgroud)
基本上,我需要设置发送严格的标题。
谢谢你们