json全称是javascript object notation,它是一种轻量化的文本数据交换格式,它独立于语言,比xml更小、更快,更易解析。
json是一种 (key, value)
的格式,类似于python 的字典,但跟字典不是一种数据结构。在python中,跟json相关的是字典和列表。
json数据格式例子:
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
访问json元素:
employees[0].lastName="Jobs"
作用:
下面直接看代码:
import json
# 从 python对象 格式化 一个 json string
person = {"name":"Sniper","age":30,"tel":["14756222","5544852"],"isonly":True}
print(person) # 输出的都转换为单引号
print(type(person))
# json.dumps(obj,indent,sort_keys=False),indent是格式化,换行+空格,sort_keys判断是否按照key来排序
jsonStr = json.dumps(person,indent=4,sort_keys=True)
print(jsonStr) # json数据都是用双引号引起来的,bool值是小写的true和false,方便和python区分开来
print(type(jsonStr))
json.dump(person,open('data.json','w'),indent=4,sort_keys=True)
# json string 转化成 python对象
s = '{"name":"Sniper","age":30,"tel":["14756222","5544852"],"isonly":true}'
pythonobj = json.loads(s)
print(pythonobj)
print(type(pythonobj))
s = '["A",1,"age",{"f":true,"l":"Sniper"}]'
pythonobj = json.loads(s)
print(pythonobj)
print(type(pythonobj))
pythonObj = json.load(open('data.json','r'))
print(pythonObj)
print(type(pythonObj))
结果:
{'name': 'Sniper', 'age': 30, 'tel': ['14756222', '5544852'], 'isonly': True}
<class 'dict'>
{
"age": 30,
"isonly": true,
"name": "Sniper",
"tel": [
"14756222",
"5544852"
]
}
<class 'str'>
{'name': 'Sniper', 'age': 30, 'tel': ['14756222', '5544852'], 'isonly': True}
<class 'dict'>
['A', 1, 'age', {'f': True, 'l': 'Sniper'}]
<class 'list'>
{'age': 30, 'isonly': True, 'name': 'Sniper', 'tel': ['14756222', '5544852']}
<class 'dict'>
Process finished with exit code 0
因篇幅问题不能全部显示,请点此查看更多更全内容