• Kivy UrlRequest 与 Python unicode 以及 json


     

    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的数据转换如下:

    JSON Python
    object dict
    array list, tuple
    string str, unicode
    number int, long, float
    true True
    false False
    null None

     

     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的逆操作。

    暂时写到这里,后面再补充。

     

     

     

     

     

     

     

     

     

  • 相关阅读:
    动态规划-重叠子问题
    百度 谷歌 Twitter,这么多短链接服务(Short Url)究竟哪家强?
    java中String初始化的两种方式
    bzoj 1218 [HNOI2003]激光炸弹
    Android TextView 横向滚动(跑马灯效果)
    混合高斯模型的EM求解(Mixtures of Gaussians)及Python实现源代码
    【Allwinner ClassA20类库分析】 2.free pascal语法及结构简析
    昂贵的聘礼
    C++11时间具体解释
    C++开发人脸性别识别教程(7)——搭建MFC框架之界面绘制
  • 原文地址:https://www.cnblogs.com/dotdog/p/4545368.html
Copyright © 2020-2023  润新知