您的位置:首页 > 编程语言 > Python开发

Kivy UrlRequest 与 Python unicode 以及 json

2015-06-02 02:22 537 查看
UrlRequest


The content is also decoded(译码) if the ContentType is application/json and the result automatically(自动地) passed through json.loads.


官方文档中举例:

def got_weather(req, results):
  for key, value in results['weather'][0].items():
    print(key, ': ', value)

req = UrlRequest('http://api.openweathermap.org/data/2.5/weather?q=Paris,fr', got_weather)


其中got_weather便是请求成功的on_success处理函数(钩子?),而got_weather中第二个参数便是请求的响应,即results

值得注意的是results是经过json.loads处理过的数据。

即”原始数据“经过处理之后变成了python对应的数据。json对应python的数据转换如下:

JSONPython
objectdict
arraylist, tuple
stringstr, unicode
numberint, long, float
trueTrue
falseFalse
nullNone
unicode

关于这部分,已经总结过了。

json

栗子:

<type 'dict'>
{u'ERRORCODE': u'63', u'RESULT': u'not matched'}

<type 'dict'>
{u'ERRORCODE': u'0', u'RESULT': {u'nickname': u'eric', u'name': u'', u'accountID': u'kPRD'}}


另一个栗子:

('===========', <type 'unicode'>, '===========')
{"ERRORCODE":"ME01023", "RESULT":"error!"}
('===========', <type 'unicode'>, '===========')
{"ERRORCODE":"0", "RESULT":{"number":"794","uniqueCode":"841"}}


(目前的理解)第一种情况很可能是传递过来的数据在json.loads之前已经是json的object对象,在ptyhon的json.loads之后类型便是dict类型,其中键值对因键和值均是‘字符串’类型而被转换成为python的unicode表现形式。如u'ERRORCODE'

第二种情况则只是json的字符串被json.loads之后转换成为unicode.

根据网友提供python中json操作实例:

#将Python dict类型转换成标准Json字符串
d={}
d['a'] =1
d['b']=2
d[3]='c'
d[4]=['k','k1']
k=JSONEncoder().encode(d)

print(type(k))
print(k)


运行结果:

<type 'str'>
{"a": 1, "3": "c", "b": 2, "4": ["k", "k1"]}


#将json字符串转换成Python dict类型
json_str='{"a":1,"b":2,"3":"c","4":["k","k1"]}'
d=JSONDecoder().decode(json_str)

print(type(d))
print(d)


运行结果:

<type 'dict'>
{u'a': 1, u'3': u'c', u'b': 2, u'4': [u'k', u'k1']}


额外地:json.dumps是json.loads的逆操作。

暂时写到这里,后面再补充。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: