gpt4 book ai didi

python - 如何用python中的列表替换json的某些键和值

转载 作者:行者123 更新时间:2023-12-05 03:17:39 25 4
gpt4 key购买 nike

{'Functions': {0: {'Function-1': {0: {'Function': 'dd', 'Function2': 'd3'}}}}}

我想从上面的 json 中删除 {0: } 项目并在该位置添加一个列表,以便该值包含在列表中,如所需输出中所示。

请注意上面的 json 是 jsondiff 的一个 put。

期望的输出

{"Functions":[{"Function-1":[{"Function":"dd","Function2":"d3"}]}]}

下面是我当前的代码:


from jsondiff import diff
json1 = json.loads("""
{
"Name": "Temperature \u0026 Pressure Measurement",
"Id": "0x0102",
"Channels": [
{
"Data": [
{
"Channel0": [
{
"Enable": 0,
"Unit": "Celsius"
}
],
"Channel1": [
{
"Enable": 0,
"Unit": "Celsius"
}
],
"Channel2": [
{
"Enable": 0,
"Unit": "Celsius"
}
]
}
]
}
],
"Events": [
{
"event1": 0,
"event2": 0
}
],
"Diagnostics": [
{
"diag1": 0,
"diag2": 0
}
],
"Functions": [
{
"Function-1": [
{
"Function": "2d"
}
]
}
]
}
""")

json2 = json.loads("""
{
"Name": "Temperature \u0026 Pressure Measurement",
"Id": "0x0102",
"Channels": [
{
"Data": [
{
"Channel0": [
{
"Enable": 0,
"Unit": "Celsius"
}
],
"Channel1": [
{
"Enable": 0,
"Unit": "Celsius"
}
],
"Channel2": [
{
"Enable": 0,
"Unit": "Celsius"
}
]
}
]
}
],
"Events": [
{
"event1": 0,
"event2": 0
}
],
"Diagnostics": [
{
"diag1": 0,
"diag2": 0
}
],
"Functions": [
{
"Function-1": [
{
"Function": "dd",
"Function2":"d3"
}
]
}
]
}
""")


# This gives the difference between the json and this is what we want to operate on ! the 'res' may vary based on the changes made to json2


res = str(diff(json1, json2))


print('----------------------')
print('------- DIFF -------')
print('----------------------')
print(f'{res}')
print('----------------------')
print('----------------------')
print('')
print('----------------------')
print('---Expected Output---')
print('----------------------')
print('{"Functions":[{"Function-1":[{"Function":"dd","Function2":"d3"}]}]}')
print('----------------------')
print('----------------------')

编辑::

更清楚的是,res 变量将始终更改。所以我认为它不能总是通过使用字符串替换来实现,因为括号的数量可能会根据 json1 和 json2 的不同而改变

最佳答案

代码:

from ndicts.ndicts import NestedDict

STEP 1//将嵌套字典转换为平面字典

fd = list(pd.json_normalize(Mydict).T.to_dict().values())[0] 
#Output {'Functions.0.Function-1.0.Function': 'dd', 'Functions.0.Function-1.0.Function2': 'd3'}

第 2 步//通过拆分/删除 0

将平面字典转换为嵌套
nd = NestedDict()
for key, value in fd.items():
n_key = tuple(key.split(".0."))
nd[n_key] = value

dic = nd.to_dict()
dic

#Output
{'Functions': {'Function-1': {'Function': 'dd', 'Function2': 'd3'}}}

STEP 3//要添加 [],您可以将 dict 转换为 json,并将 { 替换为 [{

json.loads(json.dumps(dic).replace('{','[{').replace('}','}]'))[0]

欲望输出

{'Functions': [{'Function-1': [{'Function': 'dd', 'Function2': 'd3'}]}]}

Package ref

question ref

关于python - 如何用python中的列表替换json的某些键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74052308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com