说明


JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)或者列表(list)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。

编码


  1. import json
  2. obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)}]
  3. encodejson = json.dumps(obj)
  4. print(repr(obj))
  5. print(encodejson)
  6. >>[[1, 2, 3], 123, 123.123, 'abc', {'key1': (1, 2, 3), 'key2': (4, 5, 6)}]
  7. >>[[1, 2, 3], 123, 123.123, "abc", {"key1": [1, 2, 3], "key2": [4, 5, 6]}]
  • dumps提供了很多参数可供选择,常用的有sort_keys(对dict对象进行排序),separators,indent等

    1. sort_keys 告诉编码器按照字典key排序(a到z)输出

      1. import json
      2. data1 = {'b':789,'c':456,'a':123}
      3. data2 = {'a':123,'b':789,'c':456}
      4. d1 = json.dumps(data1,sort_keys=True)
      5. d2 = json.dumps(data2)
      6. d3 = json.dumps(data2,sort_keys=True)
      7. print(d1,d2,d3)
      8. >>{"a": 123, "b": 789, "c": 456} {"a": 123, "b": 789, "c": 456} {"a": 123, "b": 789, "c": 456}
    2. indent 根据数据格式缩进显示,读起来更加清晰, indent的值,代表缩进空格式

      1. import json
      2. data1 = {'b':789,'c':456,'a':123}
      3. d1 = json.dumps(data1,sort_keys=True,indent=4)
      4. print(d1)
      5. >>>>
      6. {
      7. "a": 123,
      8. "b": 789,
      9. "c": 456
      10. }
    3. separators参数的作用是去掉‘,’ ‘:’后面的空格,在传输数据的过程中,越精简越好,冗余的东西全部去掉

      1. import json
      2. data1 = {'b':789,'c':456,'a':123}
      3. print('DATA',repr(data1))
      4. print('repr(data1)',len(repr(data1)),sep=':')
      5. print('dumps(data1)',len(json.dumps(data1)),sep=':')
      6. print('dumps(data1,separators)',len(json.dumps(data1,separators=(',',':'))),sep=':')
      7. >>>>
      8. DATA {'b': 789, 'c': 456, 'a': 123}
      9. repr(data1):30
      10. dumps(data1):30
      11. dumps(data1,separators):25
    4. 输出真正的中文需要指定ensure_ascii=False

      1. import json
      2. print(json.dumps('中国'))
      3. >>"\u4e2d\u56fd"
      4. print(json.dumps('中国',ensure_ascii=False))
      5. >>"中国"

      解码


  1. import json
  2. obj = [[1,2,3],123,123.123,'abc',{'key1':(1,2,3),'key2':(4,5,6)}]
  3. encodejson = json.dumps(obj)
  4. decodejson = json.loads(encodejson)
  5. print(decodejson)
  6. >>[[1, 2, 3], 123, 123.123, 'abc', {'key1': [1, 2, 3], 'key2': [4, 5, 6]}]

json.load()可以用来读取文件:

  1. import json
  2. with open('file.json','r') as f:
  3. result = json.load(f)

json.loads()是用来读取字符串的,如果用这个来读取文件会报错
如果strict为false(默认值为True),则字符串中允许使用控制字符。此上下文中的控制字符是那些字符代码在0–31范围内的字符,包括“\t”(制表符)、“\n”、“r”和“\0”。

  1. import json
  2. lines = []
  3. with open('file.json','r') as f:
  4. for row in f.readlines():
  5. if row.strip().startswith('//'):
  6. continue
  7. lines.append(row)
  8. result=json.loads('\n'.join(lines)) #loads是变为字符串的内容

处理自定义的对象


  1. import json
  2. class Person():
  3. def __init__(self,name,age):
  4. self.name = name
  5. self.age = age
  6. def __repr__(self):
  7. return 'Person object name is {0},age is {1}'.format(self.name,self.age)
  8. if __name__ == '__main__':
  9. p = Person('Peter',22)
  10. print(p)
  11. >>Person object name is Peter,age is 22
  12. def object2dict(obj):
  13. d = dict()
  14. d['__class__'] = obj.__class__.__name__
  15. d['__module__'] = obj.__module__
  16. d.update(obj.__dict__)
  17. return d
  18. def dict2object(d):
  19. if'__class__' in d:
  20. class_name = d.pop('__class__')
  21. module_name = d.pop('__module__')
  22. module = __import__(module_name)
  23. class_ = getattr(module,class_name)
  24. args = dict((key.encode('ascii'), value) for key, value in d.items()) #get args
  25. inst = class_(**args) #create new instance
  26. else:
  27. inst = d
  28. return inst

处理日期类型

datetime 类型无法通过json序列化,需要对其做特殊处理


  1. import json
  2. from datetime import datetime,date
  3. class DateToJson(json.JSONEncoder):
  4. def default(self,obj):
  5. if isinstance(obj,datetime):
  6. return obj.strftime("%Y年%m月%d日 %H:%M:%S")
  7. if isinstance(obj,date):
  8. return obj.strftime("%Y-%m-%d")
  9. else:
  10. return json.JSONEncoder.default(self,obj)
  11. d = {'name':'Bill','time':datetime.now()}
  12. print(json.dumps(d,cls=DateToJson,ensure_ascii=False))
  13. >>d = {'name':'Bill','time':'2022年1月16日 16:57:43'}