gpt4 book ai didi

python - 动态地在嵌套级别的字典中插入/添加 json 对象

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

我正在编写一个脚本,以根据 json 规范生成一些测试数据。这个脚本的目的是构造一个json对象/python dict record

为了简化事情,我在这里使用一个列表 items 代表我的源项目,它也代表应该插入值的路径。

这是我的预期输出 -

{
"access": {
"device": {
"java": {
"version": "Test Data"
},
"python": {
"version": "Test Data"
}
},
"type": "Test Data"
},
"item1": 1,
"item2": 0
}

我能够构建嵌套对象,但它们都被插入到字典的第一级。

如何使用 dest_path 将结果存储在预期位置?

来源:

import json
import random

def get_nested_obj(items: list):
"""
Construct a nested json object
"""

res = 'Test Data'

for item in items[::-1]:
res = {item: res}

return res

def get_dest_path(source_fields):
"""
Construct dest path where result from `get_nested_obj` should go
"""

dest_path = ''

for x in source_fields:
dest_path += f'[\'{x}\']'

return 'record'+dest_path

record = {}
items = ['access.device.java.version', 'access.device.python.version', 'access.type', 'item1', 'item2']

for item in items:
if '.' in item:
source_fields = item.split('.')

temp = record
for i, source_field in enumerate(source_fields):
if source_field in temp:
temp = temp[source_field]
continue

res = get_nested_obj(source_fields[i+1:])

dest_path = get_dest_path(source_fields[:i])
print(dest_path)

record[source_field] = res # Here's the problem. How to use dest_path here?
break
else:
record[item] = random.randint(0, 1)

print(json.dumps(record))

我的输出:

{
"access": {
"device": {
"java": {
"version": "Test Data"
}
}
},
"python": {
"version": "Test Data"
},
"type": "Test Data",
"item1": 1,
"item2": 0
}

最佳答案

要从 items 列表构造 record 字典,您可以使用下一个示例:

import random

record = {}
items = [
"access.device.java.version",
"access.device.python.version",
"access.type",
"item1",
"item2",
]

for i in items:
i = i.split(".")

if len(i) == 1:
record[i[0]] = random.randint(0, 1)
else:
r = record
for v in i[:-1]:
r.setdefault(v, {})
r = r[v]
r[i[-1]] = "Test Data"

print(record)

打印:

{
"access": {
"device": {
"java": {"version": "Test Data"},
"python": {"version": "Test Data"},
},
"type": "Test Data",
},
"item1": 1,
"item2": 1,
}

关于python - 动态地在嵌套级别的字典中插入/添加 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73871099/

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