python 解析JSON

来源:互联网 发布:欧陆天使淘宝店 编辑:程序博客网 时间:2024/06/09 18:53

导入json库

import json

json.dumps 将python 对象编码成json字符串

json.loads 将json字符串解码为python 对象


1、json.loads 用于解码python数据,该函数返回python字段的数据类型

1)读取json.log中的json字符串,提取其中的某几个字段写到excel中(测试用数据引用http://www.qqe2.com,json编辑器中数据)

#!/usr/bin/evn python#coding:utf-8import jsonimport xlwtfrom xlrd import open_workbookfrom xlutils.copy import copyrexcel = open_workbook("testExcel.xls")rows = rexcel.sheets()[0].nrowsexcel = copy(rexcel)sheet = excel.get_sheet(0)file = open("json.log",'r') #json.log中为筛选好的json字符串for line in file:resultJson = json.loads(line)if "url" in resultJson:url = resultJson["url"]sheet.write(rows,0,url)if "name" in resultJson:name = resultJson["name"]sheet.write(rows,1,name)if "array" in resultJson:jsonCheck = resultJson["array"][u"JSON校验"]sheet.write(rows,2,jsonCheck)rows += 1excel.save("testExcel.xls")



python原始类型和json类型的转化对照表

pythonjsondictobjectlist,tuplearraystr,unicodestringint,long,floatnumberTruetrueFalsefalseNonenull


2、json.dumps用于将python对象编码成json字符串

#!/usr/bin/evn python#coding:utf-8import jsondata = [{  "url": "http://qqe2.com",  "name": "ddd",  "array": {      "JSON校验": "http://jsonlint.qqe2.com/",      "Cron生成": "http://cron.qqe2.com/",      "JS加密解密": "http://edit.qqe2.com/"    },  "boolean": True,  "null": None,  "number": 123,  "object": {      "a": "b",      "c": "d",      "e": "f"    }}]printdata = json.dumps(data)print printdata

输出json字符串



PS:

实际应用中,需要解析某log中返回的某个json字符串,但该json字符串已经按照解析过的json格式多行展现,需要从这些行中提取某些字段

顾采用,读文件,取需要的行,去掉行首尾空白,拼接成json字符串

然后json.loads把json字符串解码为python对象,然后提取响应字段,写到excel中


http://www.runoob.com/python/python-json.html
http://www.pythontab.com/html/2017/pythonjichu_0413/1127.html

原创粉丝点击