我想把json数据转换成键值格式,怎么办?
我的数据
data = {
"type": "student",
"age": "17",
"sex": "male",
}
预期产出
[
{ "type": "student", "key": "age", "value": "17" },
{ "type": "student", "key": "sex", "value": "male" },
]
发布于 2022-10-04 00:57:50
您可以使用一个函数来概括您的输出,以防字典中有更多您想要按原样键入的键,或者将它们添加到您的键值对列表中。
def transfrom(data, non_key_value: list, key_value: list):
base = {key: val for key, val in data.items() if key in non_key_value}
ouput = [{**base, **{"key": val, "value": data[val]}} for val in key_value]
return ouput
transfrom(data, non_key_value=["type"], key_value=["age", "sex"])
>>>
[{'type': 'student', 'key': 'age', 'value': '17'},
{'type': 'student', 'key': 'sex', 'value': 'male'}]
发布于 2022-10-04 00:54:20
我对json不是很熟悉,而且在json
包中可能有一个函数来进行这种转换,但是这对您的数据是有效的:
data = {
"type": "student",
"age": "17",
"sex": "male",
}
out = []
for key, value in data.items():
d = {"type": data["type"]}
if key != "type":
d["key"] = key
d["value"] = value
out.append(d)
out
退出:
[{'type': 'student', 'key': 'age', 'value': '17'},
{'type': 'student', 'key': 'sex', 'value': 'male'}]
发布于 2022-10-04 01:38:41
下面是一种使用流行方法和|
操作符来完成此操作的方法:
data = {"type": "student", "age": "17", "sex": "male"}
base = {"type": data.pop("type")}
output = [base | {"key": key, "value": value} for key, value in data.items()]
print(output)
输出:
[{'type': 'student', 'key': 'age', 'value': '17'}, {'type': 'student', 'key': 'sex', 'value': 'male'}]
此代码使用pop方法从字典中删除键并返回它,这意味着"base“变为{"data": "student"}
,"data”变为{"age": "17", "sex": "male"}
。
然后,它使用一个列表理解,迭代"data“中剩余的键和值,使用|
操作符将它们与"base”中的键/值对组合起来,每次创建一个新字典。
注意:|
操作符是在Python3.9中引入的。
https://stackoverflow.com/questions/73945033
复制