获取json的value的类型
时间: 2023-12-26 15:05:31 浏览: 36
获取 JSON 的 value 的类型,我们可以使用 `type()` 函数或者 `isinstance()` 函数。
假设我们有以下 JSON 字符串:
```python
import json
data = '{"name": "Alice", "age": 18, "is_student": true, "scores": [90, 85, 92], "address": {"city": "Beijing", "street": "Haidian Road"}}'
json_data = json.loads(data)
```
我们可以使用以下代码来获取其中某个 key 对应的 value 的类型:
```python
# 获取 name 的类型
print(type(json_data['name'])) # <class 'str'>
# 获取 age 的类型
print(type(json_data['age'])) # <class 'int'>
# 获取 is_student 的类型
print(type(json_data['is_student'])) # <class 'bool'>
# 获取 scores 的类型
print(type(json_data['scores'])) # <class 'list'>
# 获取 address 的类型
print(type(json_data['address'])) # <class 'dict'>
```
如果要判断 value 的类型是否为某个类型,可以使用 `isinstance()` 函数,例如:
```python
if isinstance(json_data['name'], str):
print("name is a string")
if isinstance(json_data['age'], int):
print("age is an integer")
if isinstance(json_data['is_student'], bool):
print("is_student is a boolean")
if isinstance(json_data['scores'], list):
print("scores is a list")
if isinstance(json_data['address'], dict):
print("address is a dictionary")
```
需要注意的是,在 JSON 中,true 对应 Python 中的 True,false 对应 Python 中的 False,null 对应 Python 中的 None。