PYTHON3处理JSON的函数

时间:2022-03-24 07:19:22


PYTHON3处理JSON的函数学习python的朋友必须要挑拨的一门技巧的,我们下面给各位整理了一些处理json函数供各位参考学习。

在python3中import json模块,然后使用dir(json)可以看到json模块提供的函数,下面选几个常用的json处理函数看看用法:

>>> import json
>>> dir(json)
['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__',
'__author__', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__path__', '__spec__',
'__version__', '_default_decoder', '_default_encoder', 'decoder',
'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

json.dumps

先定义一个列表,然后转换看看输出结果:

import json

data = [{"a":"aaa","b":"bbb","c":[1,2,3,(4,5,6)]},33,'tantengvip',True]
data2 = json.dumps(data)

print(data2)
输出结果:

[{“c”: [1, 2, 3, [4, 5, 6]], “a”: “aaa”, “b”: “bbb”}, 33, “tantengvip”, true]

其实python的列表数据结构跟json数据结果很类似,转换之后大体不变,只是True变成了true,元祖类型的(4,5,6)变成了[4,5,6].

JSON PYTHON
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None
该表展现了python和json类型的转换区别。

json.dump

这个方法用的相对较少,假如直接dump(json_data)会报错,如下:

data = [{"a":"aaa","b":"bbb","c":[1,2,3,(4,5,6)]},33,'tantengvip',True]
data2 = json.dump(data)

#TypeError: dump() missing 1 required positional argument: 'fp'
报错:TypeError: dump() missing 1 required positional argument: ‘fp’

json.dump和json.dumps很不同,json.dump主要用来json文件读写,和json.load函数配合使用。json.dump(x,f),x是对象,f是一个文件对象,这个方法可以将json字符串写入到文本文件中。


import json

data = [{"a":"aaa","b":"bbb","c":[1,2,3,(4,5,6)]},33,'tantengvip',True]
data2 = json.dumps(data)

print(data2)

f = open('./tt.txt','a')
json.dump(data2,f)

这样就生成了一个tt.txt文件,保存了json格式的数据。dumps还提供pritty print,格式化的输出。

json.load加载json格式文件

f = open('./tt.txt','r')
hehe = json.load(f)

print(hehe)
这样就从txt文件中读取了json数据。

json.lodas函数

那么json.loads函数跟json.load有何区别?跟dumps和dump一样,带s是操作文件的。


hehe2 = json.loads('["aaa",{"name":"pony"}]')
print(hehe2)

loads可以直接传json格式数据作为参数。

看一个读取天气的例子

import os, io, sys, re, time, base64, json
import webbrowser, urllib.request
def main():
"main function"
url = "http://m.weather.com.cn/data/101010100.html"
stdout=urllib.request.urlopen(url)
weatherInfo= stdout.read().decode('utf-8')
#print(weatherInfo)
jsonData = json.loads(weatherInfo)


#输出JSON数据
szCity = jsonData["weatherinfo"]["city"]
print("城市: ", szCity)
szTemp = jsonData["weatherinfo"]["temp1"]
print("温度: ", szTemp)
szWeather1 = jsonData["weatherinfo"]["weather1"]
print("天气情况: ",szWeather1)
szCityid = jsonData["weatherinfo"]["cityid"]
print("城市编码: ",szCityid)

if __name__ == '__main__':
main()

 

 

转载自--http://www.alliedjeep.com/95882.htm