1 import json
2
3 a = ['qwe', '阿达', '123']
4 b = json.dumps(a, ensure_ascii=False)
5 # ensure_ascii=False,包含非ascii的字符
6 print(b, type(b))
7 c = json.loads(b)
8 print(c, type(c))
9 with open('11', 'w', encoding='utf-8') as f:
10 json.dump(a, f, ensure_ascii=False)
11 # dump,load接受一个文件句柄,直接输出输入在文件
12 with open('11', 'r', encoding='utf-8') as f:
13 print(json.load(f))
14
15 # 注意. 我们可以向同一个文件中写入多个json串. 但是读不行.
16 # dump load
17 # with open('11', 'w', encoding='utf-8') as f:
18 # json.dump('123',f)
19 # json.dump('123',f)
20 # json.dump('123',f)
21 # with open('11', 'r', encoding='utf-8') as f:
22 # print(json.load(f)) # 报错
23
24 # dumps,loads
25 with open('11', 'w', encoding='utf-8') as f:
26 s = json.dumps('123')
27 f.write(s + '\n')
28 f.write(s + '\n')
29 f.write(s + '\n')
30 with open('11', 'r', encoding='utf-8') as f:
31 for line in f:
32 print(json.loads(line.strip()))
33
34 '''
35 json其他参数
36 Serialize obj to a JSON formatted str.(字符串表示的json对象)
37 Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
38 ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\ uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。)
39 If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
40 If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
41 indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
42 separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
43 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
44 sort_keys:将数据根据keys的值进行排序。
45 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
46 '''