json

json是一个特殊的字符串。 【长的像列表/字典/字符串/数字/真假】

  • dumps and loads
import json
# 序列化,将python的值转换为json格式的字符串。
# v = [12,3,4,{'k1':'v1'},True,'asdf']
# v1 = json.dumps(v)
# print(v1)

# 反序列化,将json格式的字符串转换成python的数据类型
# v2 = '["alex",123]'
# print(type(v2))
# v3 = json.loads(v2)
# print(v3,type(v3))
    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

字典或列表中如有中文,序列化时想要保留中文显示:

v = {'k1':'alex','k2':'李杰'}
      
import json
val = json.dumps(v,ensure_ascii=False)
print(val)
  • dump
import json
      
v = {'k1':'alex','k2':'李杰'}
      
f = open('x.txt',mode='w',encoding='utf-8')
val = json.dump(v,f)  # 使用dump和load可以读写文件
print(val)
f.close()
  • load
import json
      
v = {'k1':'alex','k2':'李杰'}
      
f = open('x.txt',mode='r',encoding='utf-8')
data = json.load(f)
f.close() 
print(data,type(data))
posted @ 2019-11-12 21:26  无夜。  阅读(110)  评论(0编辑  收藏  举报