Home > other >  How to convert path into json in python?
How to convert path into json in python?

Time:11-23

I'm getting values in the below format

/a/b/c/d="value1"
/a/b/e/f="value2"

I want these values in the below format.

{
    "a": {
        "b": {
            {
                "c": {
                    "d": "value1"
                }
            },
            {
                "e" {
                    "f": "value2"
                }
            }
        }
    }

}

Are there any built-in functions in python that can do this job as I could a["b"]["c"]["d"] kind of structure is not possible in the python dictionary?

CodePudding user response:

Feels a bit hacky, but if you want to go with the a["b"]["c"]["d"] route, you could use collections.defaultdict to do it.

from collections import defaultdict

def defaultdict_factory():
    return defaultdict(defaultdict)

a = defaultdict(defaultdict_factory)

a["b"]["c"]["d"] = "value1"

CodePudding user response:

Built-in no, but you can reduce each of these expressions to a dictionary and then get their union.

from functools import reduce

data = """
/a/b/c/d="value1"
/a/b/e/f="value2"
"""

exp = dict()
for pathexp in data.strip().splitlines():
    # skip past first "/" to avoid getting an empty element
    path, value = pathexp.lstrip("/").rsplit("=", 1)
    exp.update(
        reduce(lambda x, y: {y: x}, reversed(path.split("/")),
               value.strip('"')))

print(exp)

If you really wanted to, you could fold this into a one-liner with another reduce instead of the loop; but unless you are really into functional programming, this is already rather dense.

  • Related