gpt4 book ai didi

python - 将 size = x 添加到 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:52 25 4
gpt4 key购买 nike

我有以下代码来根据 ; 分隔的数据创建 JSON 文件。导入 csv从集合导入defaultdict

def ctree():
""" One of the python gems. Making possible to have dynamic tree structure.
"""
return defaultdict(ctree)


def build_leaf(name, leaf):
""" Recursive function to build desired custom tree structure
"""
res = {"name": name}

# add children node if the leaf actually has any children
if len(leaf.keys()) > 0:
res["children"] = [build_leaf(k, v) for k, v in leaf.items()]

return res


def main(delimter):
tree = ctree()
text = """
something;cookie;chocolat
something;cookie;milk
something;gains;bread
anything;protein;chicken
"""
rows = [row.strip().split(delimter) for row in text.split("\n")]
for row in rows:
if row:
leaf = tree[row[0]]
for cid in range(1, len(row)):
leaf = leaf[row[cid]]

# building a custom tree structure
res = []
for name, leaf in tree.items():
res.append(build_leaf(name, leaf))

# printing results into the terminal
import json
print(json.dumps(res))


# so let's roll
main(";")

(来源:Convert csv to JSON tree structure?)

这将产生以下输出:

[
{
"name": ""
},
{
"name": "something",
"children": [
{
"name": "cookie",
"children": [
{
"name": "chocolat"
},
{
"name": "milk"
}
]
},
{
"name": "gains",
"children": [
{
"name": "bread"
}
]
}
]
},
{
"name": "anything",
"children": [
{
"name": "protein",
"children": [
{
"name": "chicken"
}
]
}
]
}
]

但是我想包含一个 , "size": 100,所以我有这样的输出:

[
{
"name": ""
},
{
"name": "something",
"children": [
{
"name": "cookie",
"children": [
{
"name": "chocolat", "size" : 100
},
{
"name": "milk", "size" : 100
}
]
},
{
etc.

因此,如果将项目添加到 3rd 层,实际上需要添加 , "size": 100 。我想知道使用上面的递归是否仍然可能?或者我应该将其更改为嵌套循环(我不喜欢)以便能够“记住”当前层?如果不是,我怎样才能在仍然使用递归的情况下实现这一目标

最佳答案

正如 Markaos 在评论中提到的,您只需要跟踪递归深度,以便知道何时向 res["children"] 中的每个字典添加额外的键值对。例如,

def build_leaf(name, leaf, depth=0):
""" Recursive function to build desired custom tree structure
"""
res = {"name": name}
depth += 1

# add children node if the leaf actually has any children
if len(leaf.keys()) > 0:
lst = [build_leaf(k, v, depth) for k, v in leaf.items()]
if depth >= 2:
for d in lst:
d['size'] = 100
res["children"] = lst
return res

我已将 深度 的默认值设置为零,因此您无需修改​​ main 中对 build_leaf 的调用。

生成的 JSON 如下所示(我使用自定义编码器来生成更紧凑的输出)。

[
{"name": ""},
{
"name": "something",
"children": [
{
"name": "cookie",
"children": [
{"name": "chocolat", "size": 100},
{"name": "milk", "size": 100}
]
},
{
"name": "gains",
"children": [
{"name": "bread", "size": 100}
]
}
]
},
{
"name": "anything",
"children": [
{
"name": "protein",
"children": [
{"name": "chicken", "size": 100}
]
}
]
}
]

关于python - 将 size = x 添加到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44478515/

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