您好我正在嘗試實作以下場景
樣品 1
path = "$.name"
val = ""
"""expected o/p"""
path_output = {"name":""}
路徑是我想創建我的 JSON 字典的方式,值代表預期值
樣品 2
path = "$.name.age"
val = ""
"""expected o/p"""
path_output = {"name":{ "age":""
}}
樣品 3
path = "$.name"
val = []
"""expected o/p"""
path_output = {"name":{ "age":[""]
}}
如果你能幫我解決這個問題,那用簡單的語言會很棒,我希望以相反的方式使用以下庫
from jsonpath_ng import parse
給定路徑和值我想構建我的字典
uj5u.com熱心網友回復:
這看起來像是遞回解決方案的完美候選者。這是我建議的實作:
def recursive_path2dict(path, val):
# Exit case: empty path
if path == "":
return val
# Get current node
path_elements = path.split(".")
current_node = path_elements[0]
# Reconstruct the path for the chilren nodes
children_path = ".".join(path_elements[1:])
# Recursively get children structure
children_dict = recursive_path2dict(children_path, val)
# Ignore root indicator
if current_node == "$":
return children_dict
return {current_node: children_dict}
以下是您使用此功能的示例:
recursive_path2dict("$.name", "")
>>> {'name': ''}
recursive_path2dict("$.name.age", "")
>>> {'name': {'age': ''}}
recursive_path2dict("$.name", [])
>>> {'name': []}
它們并不完全相同,但您可以根據您想要的結果涵蓋特殊情況。例如,檢查val == []并回傳[""].
希望這可以幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522834.html
上一篇:將TypeConverter用于Dictionary鍵,但不使用相同型別的Dictionary值?
下一篇:資料框中的字典值
