python操作json文件常用的四种方法为:json.loads;json.load;json.dumps;json.dump
一. json.loads()
官方给出的解释为:
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
- 1
- 2
其实就是将json对象转化内为python对象,可以理解为将字符串转换为字典,例如:
s = '{"nqme":"123","age":"123"}'
result = json.loads(s)
print(s) # {"nqme":"123","age":"123"}
print(result) # {'nqme': '123', 'age': '123'}
print(type(s)) # <class 'str'>
print(type(result)) # <class 'dict'>
- 1
- 2
- 3
- 4
- 5
- 6
二.json.load()
两个字”解码“,对json进行读取,官方给出的解释为:
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
- 1
- 2
用于对json文件的读取,例如:
result = open("keyword.json","r",encoding="utf-8")
print(type(result)) # <class '_io.TextIOWrapper'>
data = json.load(result)
print(type(data)) # <class 'list'>
- 1
- 2
- 3
- 4
三. json.dumps()
官方解释:
"""Serialize ``obj`` to a JSON formatted ``str``.
- 1
将python对象转换为json对象,可以理解为将字典转换为字符串,例如:
s = {"name":"mqy","age":"23"}
print(type(s)) # <class 'dict'>
ts = json.dumps(s)
print(type(ts)) # <class 'str'>
- 1
- 2
- 3
- 4
四. json.dump()
官方解释:
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
- 1
- 2
两个字“编码”,写入json文件,例如:
with open("number.json","a",encoding="utf-8") as f:
for i in range(10):
data = json.dump(i,fp=f)
- 1
- 2
- 3