使用python解析Json字符串-获取Json字符串关键字

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构

  1. 对象:对象在js中表示为{ }括起来的内容,数据结构为 { key:value, key:value, ... }的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象这几种。

  2. 数组:数组在js中是中括号[ ]括起来的内容,数据结构为 ["Python", "javascript", "C++", ...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种

1. json.loads()

把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:

 
  1. # json_loads.py

  2.  
  3. import json

  4.  
  5. strList = '[1, 2, 3, 4]'

  6.  
  7. strDict = '{"city": "北京", "name": "大猫"}'

  8.  
  9. json.loads(strList)

  10. # [1, 2, 3, 4]

  11.  
  12. json.loads(strDict) # json数据自动按Unicode存储

  13. # {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}

  14.  

2. json.dumps()

实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串

从python原始类型向json类型的转化对照如下:

 
  1. # json_dumps.py

  2.  
  3. import json

  4. import chardet

  5.  
  6. listStr = [1, 2, 3, 4]

  7. tupleStr = (1, 2, 3, 4)

  8. dictStr = {"city": "北京", "name": "大猫"}

  9.  
  10. json.dumps(listStr)

  11. # '[1, 2, 3, 4]'

  12. json.dumps(tupleStr)

  13. # '[1, 2, 3, 4]'

  14.  
  15. # 注意:json.dumps() 序列化时默认使用的ascii编码

  16. # 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码

  17. # chardet.detect()返回字典, 其中confidence是检测精确度

  18.  
  19. json.dumps(dictStr)

  20. # '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'

  21.  
  22. chardet.detect(json.dumps(dictStr))

  23. # {'confidence': 1.0, 'encoding': 'ascii'}

  24.  
  25. print json.dumps(dictStr, ensure_ascii=False)

  26. # {"city": "北京", "name": "大刘"}

  27.  
  28. chardet.detect(json.dumps(dictStr, ensure_ascii=False))

  29. # {'confidence': 0.99, 'encoding': 'utf-8'}

  30.  

chardet是一个非常优秀的编码识别模块,可通过pip安装

3. json.dump()

将Python内置类型序列化为json对象后写入文件

 
  1. # json_dump.py

  2.  
  3. import json

  4.  
  5. listStr = [{"city": "北京"}, {"name": "大刘"}]

  6. json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

  7.  
  8. dictStr = {"city": "北京", "name": "大刘"}

  9. json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

  10.  

4. json.load()

读取文件中json形式的字符串元素 转化成python类型

 
  1. # json_load.py

  2.  
  3. import json

  4.  
  5. strList = json.load(open("listStr.json"))

  6. print strList

  7.  
  8. # [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]

  9.  
  10. strDict = json.load(open("dictStr.json"))

  11. print strDict

  12. # {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}

转:https://blog.csdn.net/JustFORfun233/article/details/79513723

https://blog.csdn.net/kaka735/article/details/46009731

猜你喜欢

转载自blog.csdn.net/qq_39247153/article/details/81984524
今日推荐