Henkes
Henkes

Reputation: 288

dictionary to JSON?

I have the following dictionary:

terms = {"Taste Term":{'children': ['Receptor', 'Descriptor', 'Modulator', 'Tissue'], 'parent': []},"Receptor":{'children': ['ion channel'], 'parent': ['Taste Term']}, "Descriptor":{'children': [], 'parent': ['Taste Term']}, "Modulator":{'children': [], 'parent': ['Taste Term']},"Tissue":{'children': [], 'parent': ['Taste Term']}}

when I dump this dictionary with print json.dumps(terms, indent=4) i get the following Json file:

{
"Descriptor": {
    "children": [], 
    "parent": [
        "Taste Term"
    ]
}, 
"Tissue": {
    "children": [], 
    "parent": [
        "Taste Term"
    ]
}, 
"Receptor": {
    "children": [
        "ion channel"
    ], 
    "parent": [
        "Taste Term"
    ]
}, 
"Modulator": {
    "children": [], 
    "parent": [
        "Taste Term"
    ]
}, 
"Taste Term": {
    "children": [
        "Receptor", 
        "Descriptor", 
        "Modulator", 
        "Tissue"
    ], 
    "parent": []
}
}

the json file i want looks like this:

{
"name":"Taste Term",
"children": [
 {
  "name":"Receptor",
  "children": [

     {"name":"ion channel"}
   ]
  },
  {"name":"Descriptor"},
  {"name":"Modulator"},
  {"name":"Tissue"}
 ]
 }

Now, How can I edit my dictionary to get to the correct structure for Json to output the lower Json file? So I need to edit the dictionary terms in such a way that the children have the children in them.

Upvotes: 0

Views: 592

Answers (1)

martineau
martineau

Reputation: 123541

Often the simplest way to deal with recursive data structures is by using a recursive function. In this case it's possible to write one that transforms the "nodes" in the flat dictionary you have into the kind needed for the nested dictionary structure you want. Once this is done you can just json.dumps() the result to get it into JSON format.

In the code below I've corrected the syntax of the starting terms dictionary provided in your question and reformatted it to clearly show its structure.

import json

terms = {
     'root':      {'p': [],          'c': ['branch1', 'branch2', 'branch3']},
     'branch1':   {'p': ['root'],    'c': ['branch1.1']},
     'branch2':   {'p': ['root'],    'c': []},
     'branch3':   {'p': ['root'],    'c': []},
     'branch1.1': {'p': ['branch1'], 'c': []}
}

def transform(d, parent):
    return (
        {'name': parent}
            if not d[parent]['c'] else
        {'name': parent,
         'children': [transform(d, child) for child in d[parent]['c']]}
    )

print(json.dumps(transform(terms, 'root'), indent=2))

Output:

{
  "name": "root",
  "children": [
    {
      "name": "branch1",
      "children": [
        {
          "name": "branch1.1"
        }
      ]
    },
    {
      "name": "branch2"
    },
    {
      "name": "branch3"
    }
  ]
}

Upvotes: 1

Related Questions