什么是json?

json是返回的是字符串格式,把python数据类型列表、字典转换成json字符串格式, 这种格式java php 其他语言都可以认识的字符串,可以跨语言交流。

 

 json,用于字符串 和 python数据类型间进行转换

 

json.dumps() 用于将字典转换成 json 格式,但通常我们都在 json.cn 这个网站来转换
import json


data = {
    'name':'ming',
    'age':13

}

print(json.dumps(data))

f = open("BBQ.txt","w")
# f.write(str(data))
 
f.write(json.dumps(data))

f.close()


json.loads() :用于将一个 json 格式的数据转换成字典
import json

data = '{"name":"mike","age":13 }'


res = json.loads(data)
print(res)

 

json.dump() 用于把 json 格式的数据写入到文件中
import json


data = {
    'name':'ming',
    'age':13

}

with open("BBQ1.txt","w") as f:
    json.dump(data, f)

 

 
json.load() :用于把文件内中的 json 格式的数据转换成 unicode 格式的数据(unicode 是一种通用的格式)

如果文件里面有中文,需要加上encoding=“utf-8” 参数

import json


with open("BBQ1.txt", 'r',encoding="utf-8") as f:
    data = json.load(f)
    print(data)


# 执行结果
{'name': '小明', 'age': 13}

 

 

 
 

 

 

相关文章:

  • 2021-06-24
  • 2021-07-13
  • 2021-06-20
  • 2021-09-27
  • 2021-12-18
  • 2021-12-29
  • 2021-06-05
猜你喜欢
  • 2022-01-04
  • 2021-10-07
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案