Home > Software engineering >  Construct Python Dictionary from Path or JSON paths
Construct Python Dictionary from Path or JSON paths

Time:10-29

Hello i am trying to implement following scenarios

sample 1


path = "$.name"
val = ""
"""expected o/p"""
path_output = {"name":""}

Path is how i would like to create my JSON dictionary and value represent expected value

sample 2

path = "$.name.age"
val = ""
"""expected o/p"""
path_output = {"name":{ "age":""
}}

sample 3

path = "$.name"
val = []
"""expected o/p"""
path_output = {"name":{ "age":[""]
                        }}

if you can help me with this that would be great in easy language i an looking to use following library in reverse way

from jsonpath_ng import parse

given path and value i would want to construct my dict

CodePudding user response:

This looks like the perfect candidate for a recursive solution. Here's my suggested implementation:

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}

Here are your sample cases using this function:

recursive_path2dict("$.name", "")
>>> {'name': ''}

recursive_path2dict("$.name.age", "")
>>> {'name': {'age': ''}}

recursive_path2dict("$.name", [])
>>> {'name': []}

They're not exactly the same, but you can cover special cases given your desired outcome. For example, checking for val == [] and returning [""].

Hope this helps

  • Related