Json简介
Json(JavaScript Object Notation)
很多网站都会用到Json格式来进行数据的传输和交换。
这因为Json是一种轻量级的数据交换格式,具有数据格式简单,读写方便易懂等很多优点。用它来进行前后端的数据传输,大大的简化了服务器和客户端的开发工作量。
在Json中,遵循“key-value”的这样一种方式。
比如最简单的这种:“{"name" : "zhuxiao5"}”,跟python 里的字典似的,也是一个Json格式的数据。
image.png
Python3 中可以使用 json 模块来对 JSON 数据进行编解码。其中json.dumps()、json.loads()较为常用。
json.dumps() 将python对象编码成Json字符串
#json.dumps() 将python对象编码成Json字符串
import json
dict ={"name": "高小喜","age": 1}
encoded_json=json.dumps(dict,ensure_ascii=False)
print(encoded_json,type(encoded_json))
#输出的结果
=> {"name": "高小喜", "age": 1} <class 'str'>
json.loads() 将Json字符串解码成python对象
#json.loads() 将Json字符串解码成python对象
import json
decode_json=json.loads(encoded_json)
print(decode_json,type(decode_json))
#输出的结果
=>{'name': '高小喜', 'age': 1} <class 'dict'>
json.dump() 将python中的对象转化成json储存到文件中
# json.dump主要用来将python对象写入json文件
with open("demo.json", "w",encoding="utf-8") as fp:
json.dump(decode_json, fp)
fp.close()
查看demo.json文件内容如下如:
image.png
json.load() 将文件中的json的格式转化成python对象提取
# json.load加载json格式文件,返回python对象
with open("demo.json","r",encoding="utf-8") as f:
data = json.load(f)
print(data, type(data))
fp.close()
#输出的结果
=>{'name': '高小喜', 'age': 1} <class 'dict'>
完整的代码:
import json
#json.dumps() 将python对象编码成Json字符串
dict ={"name": "高小喜","age": 1}
encoded_json=json.dumps(dict,ensure_ascii=False)
print(encoded_json,type(encoded_json))
#json.loads() 将Json字符串解码成python对象
decode_json=json.loads(encoded_json)
print(decode_json,type(decode_json))
# json.dump主要用来将python对象写入json文件
with open("demo.json", "w",encoding="utf-8") as fp:
json.dump(decode_json, fp)
fp.close()
# json.load加载json格式文件,返回python对象
with open("demo.json","r",encoding="utf-8") as f:
data = json.load(f)
print(data, type(data))
fp.close()