本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于python如何读写json数据(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。json
使用 Python 语言来编码和解码 JSON 对象。
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。使用json函数需要导入json模块
将 Python 对象编码成 JSON 字符串
用于解码 JSON 数据。该函数返回 Python 字段的数据类型。
基础命令
将python对象编码成为json的字符串格式
1 2 3 4 5 6 | d = { 'name' : 'sheen' ,
'age' :17}
jsonStr = json.dumps(d) #{ "name" : "sheen" , "age" : 17} < class 'str' >
l = [1,3,5,1.2]
jsonList = json.dumps(l) #[1, 3, 5, 1.2] < class 'str' >
|
将获取的json字符串解码为python的对象
1 2 3 | pydict = json.loads(jsonStr) #{ 'name' : 'sheen' , 'age' : 17} < class 'dict' >
pylist = json.loads(jsonList) #[1, 3, 5, 1.2] < class 'list' >
|
将python对象编码成为json的字符串格式并写入文件中
1 2 | with open( 'json.txt' , 'w' ) as f :
json.dump(d,f)
|
将文件中的json字符串解码为python的对象
1 2 | with open( 'json.txt' ) as f:
jsondict = json.load(f) #{ 'name' : 'sheen' , 'age' : 17} < class 'dict' >
|
json示例
给100个不同的用户一个value值,存放到文件'json_dump.txt',并且是json格式
json.dump()参数
应该是一个非负的整型,如果是0,或者为空,则一行显示数据;否则会换行且按照indent的数量显示前面的空白
将数据根据keys的值进行排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #给100个不同的用户一个value值
#存放到文件 'json_dump.txt' ,并且是json格式
import json
import string
from random import choice
keys = [ 'user' +str(i) for i in range(100)]
values = string.ascii_lowercase+string.ascii_uppercase #大小写字符串
dict = {choice(keys):choice(values) for i in range(100)}
with open( 'json_dump.txt' , 'w' ) as f:
#indent:应该是一个非负的整型,如果是0,或者为空,则一行显示数据;否则会换行且按照indent的数量显示前面的空白
#sort_keys:将数据根据keys的值进行排序
#separators = ( "每个元素间的分隔符" , “key和value之间的分隔符”)
json.dump(dict,f,indent=4,sort_keys=True, separators=( ';' , '=' ))
#为何最后文件不够100行?
#因为随机选取的key值可能会重复,字典类型的key不允许重复,最后得到的数据会少于你给定的100次
|

查询IP地址
根据IP查询所在地、运营商等信息的一些API如下:
1 2 3 4 5 6 | 1. 淘宝的API(推荐):http:
2. 国外freegeoip.net(推荐):http:
3. 新浪的API:http:
4. 腾讯的网页查询(返回的非json格式): http:
5. ip.cn的网页(返回的非json格式):http:
6. ip-api.com: http:
|
上述的API接口,大多有一个特点是, 返回的直接是个json格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import json
from urllib.request import urlopen
# ip = input( "请输入你要查询的Ip:" )
ip = '8.8.8.8'
url = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" %(ip)
print (url)
# 根据url获取网页的内容, 并且解码为utf-8格式, 识别中文;
text = urlopen(url).read().decode( 'utf-8' )
# print (text,type(text))
data = json.loads(text)[ 'data' ]
country = data[ 'country' ]
country_id = data[ 'country_id' ]
print (country,country_id)
|

阅读剩余部分
相关阅读 >>
怎么下载官网Python并安装
Python如何求1到100的奇数和
提高Python效率的5种高级用法
Python 中的selenium异常处理
Python中绝对值怎么表示
Python中list可以修改吗
Python输出怎么取消空格
Python里有成员变量吗
Python 字典(dictionary)操作详解_Python
Python安装哪个版本
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python如何读写json数据(代码)