模块可以实现文件/字符串类型的json对象、python对象互相转换
- 查看框架版本:
json._version_一、json转换为python对象
转换类型对应表:
| json类型 | python对象类型 |
|---|---|
| object | dict |
| array | list |
| string | str |
| number(int) | int, long |
| number(float) | float |
| true | True |
| false | False |
| null | None |
1.json.load
将json文件对象转换为python对象
with open ("test.json","r") as f:
json.load(f)例如:
- test.json文件中内容为:
{
"username": "admin",
"password": "123"
}- 代码:
with open("test.json","r") as f:
data = json.load(f)
print(data)
# 结果:
# {'username': 'admin', 'password': '123'}2.json.loads
将包含json数据的字符串转换为python对象
json.loads(s,encoding="utf-8")s还可以是bytes和bytearray
例如:
- s是str
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
text = json.loads(jsonData)
print(text)
# 结果:
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
jsonData = '"123"'
text = json.loads(jsonData)
print(text)
# 结果:
# 123二、python对象转换为json
转换类型对应表:
| python对象类型 | json类型 |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, long, float | number |
| True | true |
| False | false |
| None | none |
1.json.dump
将python对象转换成json文件
json.dump(obj, filestream, indent=None, separators=None, sort_keys=False)- indent指定缩进:
- indent为正整数或者字符串(如
"#","\t"等)时,用于美化缩进 - indent为
0、负整数、""时,缩进为0,只换行 - indent为
None时,采用最紧凑表达
- separators指定分隔符:separators默认为
(", ", ": "),当indent被指定(涉及换行时),separators默认为(",", ": "),即逗号后少了个空格 - sort\_keys指定是否按照键排序
例如:
data = {"China": "Beijing", "Japan": "Tokyo", "Russia": "Moscow", "North Korea": "Pyongyang"}
with open('test.json','w') as f:
json.dump(data,f,indent=2,separators=(';',':'),sort_keys=True)
# 结果:
# {
# "China":"Beijing";
# "Japan":"Tokyo";
# "North Korea":"Pyongyang";
# "Russia":"Moscow"
# }2.json.dumps
将python对象转换成json字符串
json.dumps(obj, indent=None, separators=None, sort_keys=False, encoding='utf-8')例如:
data = [{'a':1,'b':2,'c':3,'d':4,'e':5}]
data_new = json.dumps(data)
print(data_new)
# 输出:[{"a":1,"b":2,"c":3,"d":4,"e":5}]格式化输出:
data = json.dumps({'b':'Runoob','a':7},sort_keys=True,indent=4,separators=(',',':'))
# 输出:
# {
# "a":7,
# "b":"Runoob"
# }