本篇文章简单介绍下python 中的json 解析.
import json
data = {'name': 'mars', 'age': 26}
json1 = json.dumps(data)
print("json数据:", json1)
print("原数据:", data)
输出如下:
json数据: {"name": "mars", "age": 26}
原数据: {'name': 'mars', 'age': 26}
可以看到简单类型通过编码后,json 对象与字典数据输出类似.
import json
data = {'name': 'mars', 'age': 26}
json1 = json.dumps(data)
print("json数据:", json1)
print("原数据:", data)
print(type(json1))
loads = json.loads(json1)
print("laods:", loads)
print(type(loads))
输出如下:
json数据: {"name": "mars", "age": 26}
原数据: {'name': 'mars', 'age': 26}
<class 'str'>
laods: {'name': 'mars', 'age': 26}
<class 'dict'>
可以看到 loads 函数 将JSON数据重新解码为Python字典.
with open('test.json', 'r') as test:
print(json.load(test))
with open('test.json', 'w') as test:
json.dump(json1, test)
需要注意: test.json 如果为空.
Traceback (most recent call last):
File "/home/zh/workSpace/python/Test1/venv/jsonTest1.py", line 23, in <module>
test11 = json.load(test)
File "/usr/lib/python3.8/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)