def json_rect(in_json_path,label_name): with open(in_json_path, "r", encoding='utf-8') as f: json_data = json.load(f)
时间: 2024-01-03 22:04:21 浏览: 38
这是一个 Python 函数,其作用是读取指定路径下的 JSON 文件,并返回一个包含指定标签名的 JSON 对象。
函数有两个参数:
- `in_json_path`:表示输入 JSON 文件的路径。
- `label_name`:表示要提取的 JSON 对象的标签名。
函数的实现过程如下:
1. 使用内置函数 `open()` 打开指定路径下的 JSON 文件,并以只读模式读取文件内容。
2. 使用 `json.load()` 函数将读取到的 JSON 字符串转换成 Python 对象,存储在 `json_data` 变量中。
3. 使用 `label_name` 参数提取 `json_data` 中指定标签的 JSON 对象,并将其返回。
具体实现如下:
```python
import json
def json_rect(in_json_path, label_name):
with open(in_json_path, "r", encoding='utf-8') as f:
json_data = json.load(f)
return json_data[label_name]
```
使用示例:
```python
json_obj = json_rect("example.json", "person")
print(json_obj)
```
假设 `example.json` 文件内容如下:
```json
{
"person": {
"name": "Tom",
"age": 18,
"gender": "male"
},
"pet": {
"type": "dog",
"name": "Lucky",
"age": 3
}
}
```
则以上代码输出结果为:
```
{'name': 'Tom', 'age': 18, 'gender': 'male'}
```