0

I have a string list (value) of a particular key like below

"versions": [
     "aaa/bbb/202007/cc/dd/v20",
     "aaa/bbb/202007/cc/dd/v22",
     "aaa/bbb/202007/cc/dd/v35",
     "aaa/bbb/202008/cc/dd/v15",
     "aaa/bbb/202008/cc/dd/v20",
     "aaa/bbb/202009/cc/dd/v5",
     "aaa/bbb/202009/cc/dd/v8"
]

Need this to be converted like below JSON like below

{
    "2020" : {
                 "07": {"v20", "v22", "v35"},
                 "08": {"v15", "v20"},
                 "09": {"v5", "v8"}
             },
}

What would be the best way to do this in Python

0

2 Answers 2

1

Maybe you are looking for something like this:

versions= [
     "aaa/bbb/202007/cc/dd/v20",
     "aaa/bbb/202007/cc/dd/v22",
     "aaa/bbb/202007/cc/dd/v35",
     "aaa/bbb/202008/cc/dd/v15",
     "aaa/bbb/202008/cc/dd/v20",
     "aaa/bbb/202009/cc/dd/v5",
     "aaa/bbb/202009/cc/dd/v8"
]

import json

result = dict()
for s in versions:
    l = s.split('/')
    if not l[2][:4] in result:
        result[l[2][:4]] = dict()
    if not l[2][4:] in result[l[2][:4]]:
        result[l[2][:4]][l[2][4:]] = []
    result[l[2][:4]][l[2][4:]].append(l[5])
json.dumps(result)

returning:

'{"2020": {"07": ["v20", "v22", "v35"], "08": ["v15", "v20"], "09": ["v5", "v8"]}}'
Sign up to request clarification or add additional context in comments.

Comments

0

Being a list, here's what a reducer can do with it. Easily destructure your list elements split by slashes and process the individual chunks.

reduce takes in a function to collect your results into a format (in your case JSON object / dict) and the list itself. The third param {} is an empty dict (or JSON object) wherein you process and add your data - its called accumulator. End of it, you'll get the accumulated value as result.

from functools import reduce

arr = [
    "aaa/bbb/202007/cc/dd/v20",
    "aaa/bbb/202007/cc/dd/v22",
    "aaa/bbb/202007/cc/dd/v35",
    "aaa/bbb/202008/cc/dd/v15",
    "aaa/bbb/202008/cc/dd/v20",
    "aaa/bbb/202009/cc/dd/v5",
    "aaa/bbb/202009/cc/dd/v8"
]


def convert(my_dict, entry):
    p, q, year, s, t, version = entry.split("/")
    key, internal_key = year[:4], year[4:]
    top_level_dict = my_dict.get(key, {})

    interim_dict = top_level_dict.get(internal_key, set())
    interim_dict.add(version)

    top_level_dict[internal_key] = interim_dict
    my_dict[key] = top_level_dict
    return my_dict

print(reduce(convert, arr, {}))

And the result:

{'2020': {'07': {'v22', 'v20', 'v35'}, '08': {'v15', 'v20'}, '09': {'v8', 'v5'}}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.