1、json作用
存储数据与数据传输
2、python中的json可以在代码中用字符串表示,字符串内部类似于字典
如:
json1 = '{"name":"Bob","age":1}
3、加载json文件至字典并打印
import json
json1 = '{"name":"Bob","age":1}'
json1_dict = json.loads(json1)
print(json1_dict)
4、读取外部json文件,外部json文件格式类似于字典
外部json文件js2:
{
"name":"Bob",
"age":18
}
python文件读取json文件:
import json
with open("js2.json") as js:
data = json.load(js)
print(data)
5、生成json字符串:
import json
js_dict = {"name":"Bob", "age": 12}
js_json = json.dumps(js_dict)
print(js_json)
6、python对象与json对象的对应关系
dict -- object
list,tuple -- array
str -- string
int,float -- number
True -- true
False -- false
None -- null
7、写入数据到json文件中
import json
js_dict = {
"name": "Bob",
"age": 18,
"men": True,
"language": ["python", "C++"],
"famliies": ("Mom", "Dad", "Son"),
"HasWife":None,
}
with open("js.txt", 'w') as json_file:
json.dump(js_dict,json_file)
输出结果:
{"name": "Bob", "age": 18, "men": true, "language": ["python", "C++"], "famliies": ["Mom", "Dad", "Son"], "HasWife": null}
8、格式化打印json数据
import json
js_string = '{"name": "Bob","language": ["python", "C++"]}'
js_dict = json.loads(js_string)
print(json.dumps(js_dict, indent=4, sort_keys=True))
输出结果:
{
"language": [
"python",
"C++"
],
"name": "Bob"
}