1

I am stuck on convert jsons from regular (key-value) to nested. for example:

j = { 'a': 5,
      'b': 3,
      'c.c1': 2,
      'c.c2':5,
      'd.dd.d1': 0,
      'd.dd.d2':9
    }

and I need to get:

new_j = { 
      'a': 5,
      'b': 3,
      'c': 
           {'c1': 2,
            'c2':5}
      'd': 
           {'dd' :
                 {'d1': 0,
                  'd2': 9}
            },
    }

there are easy method to do this?

2
  • 2
    what is your input? what methods do you use? Commented Apr 23, 2020 at 20:15
  • 1
    What is the issue, exactly? Please see How to Ask, help center. Commented Apr 23, 2020 at 21:09

2 Answers 2

1

How about this?

j_new = {}
for key,value in j.items():
      keys = key.split('.')
      level = j_new
      for key in keys[:-1]:
          if key not in level:
              level[key]={}
          level = level[key]
      level[keys[-1]]=value

print(j_new)

Which returns:

{'a': 5, 'b': 3, 'c': {'c1': 2, 'c2': 5}, 'd': {'dd': {'d1': 0, 'd2': 9}}}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

d = {}
def setValue(dic, keys, value):
    for key in keys[:-1]:
        dic = dic.setdefault(key, {})
    dic[keys[-1]] = value
for k,v in j.items():
    setValue(d, k.split('.'), v)

Output:

{
    "a": 5,
    "c": {
        "c2": 5,
        "c1": 2
    },
    "b": 3,
    "d": {
        "dd": {
            "d2": 9,
            "d1": 0
        }
    }
}

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.