import json
# 原始 JSON 数组(示例)
json_array = [
{"key": "name", "value": "Alice"},
{"key": "age", "value": 25},
{"key": "city", "value": "Beijing"}
]
# 转换为字典对象
result_dict = {}
for item in json_array:
result_dict[item["key"]] = item["value"]
# 转为 JSON 字符串(可选)
json_output = json.dumps(result_dict, indent=4, ensure_ascii=False)
print(json_output)
输出:
{
"name": "Alice",
"age": 25,
"city": "Beijing"
}
特点:
key
和 value
result_dict = {item["key"]: item["value"] for item in json_array}
json_output = json.dumps(result_dict, indent=4)
特点:
reduce
函数(函数式编程)from functools import reduce
result_dict = reduce(
lambda obj, item: {**obj, item["key"]: item["value"]},
json_array,
{}
)
特点:
filter
)进行数据预处理键名重复问题:
key
,后出现的值会覆盖先前的值。需提前检查:keys = [item["key"] for item in json_array]
if len(keys) != len(set(keys)):
print("存在重复键名!")
特殊数据类型处理:
value
可能是嵌套对象或数组,转换时会保留原始结构default
参数:json.dumps(result_dict, default=lambda x: x.isoformat() if hasattr(x, 'isoformat') else str(x))
输出格式化优化:
indent=4
:美化输出,带缩进ensure_ascii=False
:支持中文等非 ASCII 字符sort_keys=True
:按键名字母排序输出import json
# 输入数据
json_array = [
{"key": "product", "value": "笔记本电脑"},
{"key": "price", "value": 5999},
{"key": "in_stock", "value": True},
{"key": "specs", "value": {"CPU": "i7", "RAM": "16GB"}}
]
# 转换为字典
result_dict = {item["key"]: item["value"] for item in json_array}
# 输出为格式化的 JSON 字符串
json_output = json.dumps(
result_dict,
indent=4,
ensure_ascii=False,
sort_keys=True
)
print(json_output)
输出:
{
"in_stock": true,
"price": 5999,
"product": "笔记本电脑",
"specs": {
"CPU": "i7",
"RAM": "16GB"
}
}
import pandas as pd
df = pd.DataFrame(json_array)
df.set_index("key")["value"].to_dict() # 直接转为字典
方法 | 适用场景 | 优势 |
---|---|---|
循环遍历 | 兼容旧版 Python,逻辑清晰 | 易于调试,显式控制流程 |
字典推导式 | Python 3.6+,代码简洁化 | 高效单行实现 |
reduce 函数 |
函数式编程场景,复杂数据处理 | 支持链式操作和预处理 |
选择方法时:
reduce
函数 或结合 json.dumps
的参数定制输出格式。