• json格式转换(json,csjon)(天气预报)


    json格式数据默认为string,可以使用eval()函数或者json模块将其转换为dict.标准Json字符串必须使用双引号(")而不能使用单引号('),否则从字符串转换成dict类型会提示出错。

    方法一(使用eval函数):

    # -*- coding: UTF-8 -*-
    import urllib2
    
    url='http://www.weather.com.cn/data/cityinfo/101010100.html'
    req = urllib2.Request(url)
    res = urllib2.urlopen(req).read()
    res_d = eval(res) # use eval() to convert json string to dict. eval():将字符串str当成有效的表达式来求值并返回计算结果
    
    print type(res_d)
    print res_d['weatherinfo']['city']
    print res_d['weatherinfo']['temp1']
    print res_d['weatherinfo']['temp2']

     返回结果:

    <type 'dict'>

    北京
    -2℃
    16℃

    方法二(使用JSONDecoder):

    # -*- coding: UTF-8 -*-
    
    import urllib2,sys
    from json import *
    
    reload(sys)
    sys.setdefaultencoding('utf-8')
    
    url='http://www.weather.com.cn/data/cityinfo/101010100.html'
    req = urllib2.Request(url)
    res = urllib2.urlopen(req).read()
    res_d = JSONDecoder().decode(res)
    
    print type(res_d)
    print res_d['weatherinfo']['city']
    print res_d['weatherinfo']['temp1']
    print res_d['weatherinfo']['temp2']

     将dict转换为json:

    JSONEncoder().encode(res_d)

    方法三(使用json):

    #dict convert to json string.
    res = json.dumps(res_d)
    print type(res)
    
    #json string convert to dict.
    res_d = json.loads(res)
    print type(res_d)

    附:

    res返回值(json):

    {"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"-2℃","temp2":"16℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}

    res_d返回值(dict):

    {u'weatherinfo': {u'city': u'u5317u4eac', u'ptime': u'18:00', u'cityid': u'101010100', u'temp2': u'16u2103', u'temp1': u'-2u2103', u'weather': u'u6674', u'img2': u'd0.gif', u'img1': u'n0.gif'}}

    当使用json.loads时,如果原字符串中包含有 等字符,则会提示报错,解决办法:

    d3='{"EventTime":"2016-05-13 08:51:01","Hostname":"PC-L","Keywords":-9214364837600034816,"EventType":"AUDIT_SUCCESS","SeverityValue":2,"Severity":"INFO","EventID":4634,"SourceName":"Microsoft-Windows-Security-Auditing","ProviderGuid":"{54849625-5478-4994-A5BA-3E3B0328C30D}","Version":0,"Task":12545,"OpcodeValue":0,"RecordNumber":1053242,"ProcessID":776,"ThreadID":20412,"Channel":"Security","Message":"已注销帐户。
    
    使用者:
    	安全 ID:		S-1-5-21-3510791965-1333398612-533843580-1003
    	帐户名:		taskuser
    	帐户域:		PC-L
    	登录 ID:		0x2305C35
    
    登录类型:			4
    
    在登录会话被破坏时生成此事件。可以使用登录 ID 值将它和一个登录事件准确关联起来。在同一台计算机上重新启动的区间中,登录 ID 是唯一的。","Category":"注销","Opcode":"信息","TargetUserSid":"S-1-5-21-3510791965-1333398612-533843580-1003","TargetUserName":"taskuser","TargetDomainName":"PC-L","TargetLogonId":"0x2305c35","LogonType":"4","EventReceivedTime":"2016-05-18 15:38:35","SourceModuleName":"secin","SourceModuleType":"im_msvistalog"}'
    
    j=json.loads(d3,strict=False,encoding='utf-8')
    #j=json.loads(d3.replace('
    ','\r').replace('
    ','\n').replace('	','\t')) #将
    	字符替换掉也可以
    print type(j) #返回值:<type 'dict'>
    print j['Opcode'].encode('u8') #返回值:信息

    参数strict=False 说明:

    "If strict is False (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including ' ' (tab), ' ', ' ' and ''."

     json.dumps()包含有中文解决办法:

    d={"s-ip": "10.160.3.3", "c-ip": "10.16.100.24", "cs-username": "mail.xin.com张三"}
    dsr = json.dumps(d,ensure_ascii=False,indent=2) #indent=2表示每行缩进两个字符
    print dsr
    #返回:
    {
      "c-ip": "10.16.100.24", 
      "s-ip": "10.16.3.3", 
      "cs-username": "mail.xin.com\张三"
    }

    cjson应用:

    cjson.decode(str):将字符串转换为字典,相当于json.loads(str)。

    cjson.encode(dict):将字典转换为字符串,相当于json.dumps(dict)。

    json.load(fo),打开一个文件流,如fo=open(file,'rb'),文件中只能有一个{},不能包含有多行{},jeson.loads直接转换string,每次转换一行。

    如果str是一种非Unicode的普通含中文的json字符串,直接使用cjson.decode(str)时,会出现中文乱码。解决方法时先将str转换为Unicode格式,再进行decode,如:
    cjson.decode(str.decode('utf8'))

    cjson比json效率要高,decode 30w行数据,json.loads()耗时约7s,csjon.decode()耗时约2s

    cjson下载地址:http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-cjson

    Python3下面可以使用ujson,安装:pip3 install ujson

    示例如下:

    filepath = 'e:\logtest\iis__20160519105745.json' #此为iis转换后的json log。
    def query(filepath):
        with open(filepath,'rb') as fo:
            for line in fo:
                #lj = json.loads(line) #使用json
                lj = cjson.decode(line) #使用cjson
                if lj[u'sc-status'] == 401 and lj['cs-username'] is not None and lj['cs-username'] is not None:
                    if lj[u'cs-uri-query'].find('DeviceType') <> -1:
                        line_d = {}
                        line_d['s-ip'] = lj[u's-ip']
                        line_d['s-date'] = lj[u'date']
                        line_d['time'] = lj[u'time']
                        line_d['c-ip'] = lj[u'c-ip']
                        line_d['cs-username'] = lj['cs-username']
                        line_d['DeviceType'] = lj[u'cs-uri-query'].split('DeviceType=')[1].split('&')[0]
                        #print line_d
    query(filepath)

    cjson.encode()没有其他参数,当dict中的value含有中文时,转换后为"mail.x.com\u738bu5b50u7426",重新decode()后还是如此,最后再通过dict['key'].encode('u8')后会重新显示为中文,示例:

    #-*- coding: UTF-8 -*-
    d={"cs-username": u"mail.x.com张三"}
    
    print cjson.encode(d) #返回{"cs-username": "mail.x.com\u5f20u4e09"}
    print cjson.decode(cjson.encode(d).decode('u8')) #先decode为u8类型。返回{'cs-username': u'mail.x.com\u5f20u4e09'},value部分自动转换为unicode格式
    print cjson.decode(cjson.encode(d))["cs-username"].encode('u8') #返回mail.x.com张三

    eval()函数用法:http://www.tuicool.com/articles/BBVnQbq

    JSON 格式转换:from:http://liuzhijun.iteye.com/blog/1859857

    将python中的dict通过response返回给WEB前端时,不能直接使用dict格式,具体可见实例(ajax返回多个值(json格式))http://www.cnblogs.com/dreamer-fish/p/5441898.html

    序列化(Serialization):将对象的状态信息转换为可以存储或可以通过网络传输的过程,传输的格式可以是JSON、XML等。反序列化就是从存储区域(JSON,XML)读取反序列化对象的状态,重新创建该对象。

    JSON(JavaScript Object Notation):一种轻量级数据交换格式,相对于XML而言更简单,也易于阅读和编写,机器也方便解析和生成,Json是JavaScript中的一个子集。

    Python2.6开始加入了JSON模块,无需另外下载,Python的Json模块序列化与反序列化的过程分别是 encoding和 decoding

    encoding:把一个Python对象编码转换成Json字符串,json.dumps()
    decoding:把Json格式字符串解码转换成Python对象,json.loads()

    json是一个字符串,dict是一个字典,格式不同,但看起来长得相同。
    对于简单数据类型(string、unicode、int、float、list、tuple、dict),可以直接处理。

    json.dumps方法对简单数据类型encoding:
    import json
    data = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象
    print "DATA:",repr(data)
    
    data_string = json.dumps(data)
    print "JSON:",data_string
    

    输出:

    DATA: [{'a':'A','c':3.0,'b':(2,4)}] #python的dict类型的数据是没有顺序存储的
    JSON: [{"a":"A","c":3.0,"b":[2,4]}]  
    

    JSON的输出结果与DATA很相似,除了一些微妙的变化,如python的元组类型变成了Json的数组

    json.loads方法处理简单数据类型的decoding(解码)转换
    import json
    data = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象
    
    data_string = json.dumps(data)
    print "ENCODED:",data_string
    
    decoded = json.loads(data_string)
    print "DECODED:",decoded
    
    print "ORIGINAL:",type(data[0]['b'])
    print "DECODED:",type(decoded[0]['b'])
    

    输出:

    ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}]
    DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]
    ORIGINAL: <type 'tuple'>
    DECODED: <type 'list'>
    

    解码过程中,json的数组最终转换成了python的list,而不是最初的tuple类型

  • 相关阅读:
    NLPIR的语义分析系统
    [译] 12步轻松搞定python装饰器
    python实现爬取千万淘宝商品的方法_python_脚本之家
    Deep Learning(深度学习)学习笔记整理系列 | @Get社区
    那些年,曾经被我们误读的大数据
    值得关注的10个python语言博客
    淘宝的评论归纳是如何做到的?
    pycharm激活码
    Windows下配置Qt 5.8+opencv 3.1.0开发环境
    Ubuntu安装opencv3.1.0后配置环境变量
  • 原文地址:https://www.cnblogs.com/dreamer-fish/p/5377603.html
Copyright © 2020-2023  润新知