本文实例讲述了Python使用内置json模块解析json格式数据的方法。分享给大家供大家参考,具体如下:
Python中解析json字符串非常简单,直接用内置的json模块就可以,不需要安装额外的模块。
一、json字符串转为python值
json字符串:
复制代码 代码如下:
{"userAccount":"54321","date":"2016-12-06 10:26:17","ClickTime": 1480991177,"jsonInfo":{"lon":121.5612,"lat":31.1832,"isGps":1,"netType":"WIFI","addr":"浦东新区长江南路1099弄56号"}}
格式化一下:
1
2
3
4
5
6
7
8
9
10
11
12
|
{ "userAccount" : "54321" , "date" : "2016-12-06 10:26:17" , "ClickTime" : 1480991177, "jsonInfo" : { "lon" : 121.5612, "lat" : 31.1832, "isGps" : 1, "netType" : "WIFI" , "addr" : "浦东新区长江南路1099弄56号" } } |
1
2
3
4
5
|
# -*- coding:gbk -*- import json sJOSN = '{"userAccount":"54321","date":"2016-12-06 10:26:17","ClickTime": 1480991177,"jsonInfo":{"lon":121.5612,"lat":31.1832,"isGps":1,"netType":"WIFI","addr":"浦东新区长江南路1099弄56号"}}' sValue = json.loads(sJOSN) print (sValue) |
输出:
1
2
3
|
= = = = = = = = = = = = = RESTART: C:\Users\Administrator\Desktop\Python.py = = = = = = = = = = = = = { 'jsonInfo' : { 'lat' : 31.1832 , 'isGps' : 1 , 'netType' : 'WIFI' , 'addr' : '浦东新区长江南路1099弄56号' , 'lon' : 121.5612 }, 'ClickTime' : 1480991177 , 'userAccount' : '54321' , 'date' : '2016-12-06 10:26:17' } >>> |
对比一下原始字符串和输出的,发现前后顺序变了,因为在转化为python的字典数据的过程中,顺序会变化。
另外,json中的双引号都改成了单引号。
二、python值转为json字符串
1
2
3
4
5
|
# -*- coding:gbk -*- import json sDict = { 'jsonInfo' : { 'netType' : 'WIFI' , 'lat' : 31.1832 , 'addr' : '浦东新区长江南路1099弄56号' , 'isGps' : 1 , 'lon' : 121.5612 }, 'userAccount' : '54321' , 'ClickTime' : 1480991177 , 'date' : '2016-12-06 10:26:17' } sValue = json.dumps(sDict) print (sValue) |
输出:
又从字典数据变为了json字符串。
三、解析json中的数据
1
2
3
4
5
6
7
8
9
10
11
|
# -*- coding:gbk -*- import json sJOSN = '{"userAccount":"54321","date":"2016-12-06 10:26:17","ClickTime": 1480991177,"jsonInfo":{"lon":121.5612,"lat":31.1832,"isGps":1,"netType":"WIFI","addr":"浦东新区长江南路1099弄56号"}}' sValue = json.loads(sJOSN) for k in sValue.keys(): if str ( type (sValue[k]))! = "<class 'dict'>" : print (k + ':' + str (sValue[k])) else : print ( str (k) + ':' ) for k1 in sValue[k].keys(): print ( ' ' * 3 + k1 + ':' + str (sValue[k][k1])) |
输出:
1
2
3
4
5
6
7
8
9
10
|
= = = = = = = = = RESTART: C:\Users\Administrator\Desktop\Python json转为字典.py = = = = = = = = = userAccount: 54321 date: 2016 - 12 - 06 10 : 26 : 17 jsonInfo: netType:WIFI addr:浦东新区长江南路 1099 弄 56 号 lon: 121.5612 lat: 31.1832 isGps: 1 ClickTime: 1480991177 |
希望本文所述对大家Python程序设计有所帮助。