JSON介绍

Screenshot_20210530_105043_tv.danmaku.bili.jpgScreenshot_20210530_105359_tv.danmaku.bili.jpgScreenshot_20210530_105521_tv.danmaku.bili.jpgScreenshot_20210530_105638_tv.danmaku.bili.jpg

json&python数据类型转换

将数据从python转换到json格式,在数据类型上会有变化,如下图所示:

python json
dict object
list,tuple array
str string
int,float,int-&float-derived Enums number
True true
False false
None null

反过来,从json格式转化为python内置类型,见下表:

json python
object dict
array list
string str
number(int) int
number(real) float
true True
false False
null None

json使用方法

json模块的使用其实很简单,对于绝大多数场合下,我们只需要使用下面四个方法就可以了:

方法 功能
json.dump(obj,fp) 将python数据类型转换并保存到json格式的文件内
json.dumps(obj) 将python数据类型转换为json格式的字符串
json.load(fp) 从json格式的文件中读取数据并转换为python数据类型
json.loads(s) 将json格式的字符串转换为python数据类型

代码练习1

  1. import json
  2. ### python对象 格式化为 json string
  3. person = {'name':'baidu','age':38,'tel':['12345678911','13311223344'],'isonly':True}
  4. print(person)
  5. # 输出结果:{'name': 'baidu', 'age': 38, 'tel': ['12345678911', '13311223344'], 'isonly': True}
  6. jsonstr = json.dumps(person)
  7. print(jsonstr)
  8. # 输出结果:{"name": "baidu", "age": 38, "tel": ["12345678911", "13311223344"], "isonly": true}
  9. print(type(jsonstr))
  10. # 输出结果: <class 'str'>
  11. print(type(person))
  12. # 输出结果:<class 'dict'>
  13. ### 输出格式美化
  14. jsonStr = json.dumps(person,indent=4,sort_keys=True)
  15. print(jsonStr)
  16. # 输出结果:
  17. # {
  18. # "age": 38,
  19. # "isonly": true,
  20. # "name": "baidu",
  21. # "tel": [
  22. # "12345678911",
  23. # "13311223344"
  24. # ]
  25. # }

Screenshot_20210530_110454_tv.danmaku.bili.jpg
snapshot_2021-05-30-11-09-55.png

代码练习2

  1. import json
  2. ### json.dump(obj,fp)方法
  3. person = {'name':'baidu','age':38,'tel':['12345678911','13311223344'],'isonly':True}
  4. json.dump(person,open('data.json','w'))
  5. # 输出结果:data.json
  6. # {"name": "baidu", "age": 38, "tel": ["12345678911", "13311223344"], "isonly": true}
  7. json.dump(person,open('data1.json','w'),indent=4)
  8. # 输出结果:data1.json
  9. # {
  10. # "name": "baidu",
  11. # "age": 38,
  12. # "tel": [
  13. # "12345678911",
  14. # "13311223344"
  15. # ],
  16. # "isonly": true
  17. # }

snapshot_2021-05-30-11-12-45.png

代码练习3

  1. import json
  2. ### json字符串转换为python对象
  3. str = '{"name":"baidu","age":38,"tel":["12345678911","13311223344"],"isonly":true}'
  4. print(str)
  5. pythonObj = json.loads(str)
  6. print(pythonObj)
  7. ### 输出结果:(注意观察引号、true、True的区别)
  8. # {"name":"baidu","age":38,"tel":["12345678911","13311223344"],"isonly":true}
  9. # {'name': 'baidu', 'age': 38, 'tel': ['12345678911', '13311223344'], 'isonly': True}

snapshot_2021-05-30-11-14-17.png

代码练习4

  1. ### json.load(fp)的用法
  2. import json
  3. pythonObj = json.load(open('data.json','r'))
  4. print(pythonObj)
  5. print(type(pythonObj))
  6. # <class 'dict'>

snapshot_2021-05-30-11-15-48.png

视频

视频地址:https://b23.tv/CfBePE