Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create hierarchical json dump from list of dictionary in python

Tags:

python

json

flask

The table:

categories = Table("categories", metadata,
                   Column("id", Integer, primary_key=True),
                   Column("name", String),
                   Column("parent_id", Integer, ForeignKey("categories.id"),
                          CheckConstraint('id!=parent_id'), nullable=True),

)

A category can have many children, but only 1 parent. I have got the list of dictionary values as follows using CTE: eg. For id :14, parent is 13 and traversed from parent 8->10->12->13->14 where parent 8 has no parent id.

[
    {
      "id": 14, 
      "name": "cat14", 
      "parent_id": 13, 
      "path_info": [
        8, 
        10, 
        12, 
        13, 
        14
      ]
    }, 
    {
      "id": 15, 
      "name": "cat15", 
      "parent_id": 13, 
      "path_info": [
        8, 
        10, 
        12, 
        13, 
        15
      ]
    }
  ]

I would like to get the attributes of the parent also embedded as subcategories in the list as:

{
  "id": 14, 
  "name": "cat14", 
  "parent_id": 13, 
  "subcats": [
       {
         "id: 8", 
         "name": "cat8", 
         "parent_id":null
       }, 
       {
         "id: 10", 
         "name": "cat10", 
         "parent_id":8
       },  
       {
         "id: 12", 
         "name": "cat12", 
         "parent_id":10
       },   
      and similarly for ids 13 and 14..... 
     ]
}, 
{
  "id": 15, 
  "name": "cat15", 
  "parent_id": 13, 
  "subcats": [
       {
         "id: 8", 
         "name": "cat8", 
         "parent_id":null
       }, 
       {
         "id: 10", 
         "name": "cat10", 
         "parent_id":8
       },  
       {
         "id: 12", 
         "name": "cat12", 
         "parent_id":10
       },   
       and similarly for ids 13, 14, 15..... 
     ]
}

] Notice that 'path_info' has been deleted from the dictionary and each id has been displayed with its details. I want json dumps with the above indented format. How to go about? Using flask 0.10, python 2.7

like image 427
user956424 Avatar asked Mar 14 '16 09:03

user956424


People also ask

Can you JSON dump a list?

To convert a Python List to JSON, use json. dumps() function. dumps() function takes list as argument and returns a JSON String.

Can we convert dictionary to JSON in Python?

Python possesses a default module, 'json,' with an in-built function named dumps() to convert the dictionary into a JSON object by importing the "json" module. "json" module makes it easy to parse the JSON strings which contain the JSON object.

How do you write a dictionary into a JSON file?

You can save the Python dictionary into JSON files using a built-in module json. We need to use json. dump() method to do this. Use the indent parameter to prettyPrint your JSON data.

Is JSON a list of dictionaries?

JSON FormatJSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists. Here is a simple example with just 4 attribute/value pairs.


1 Answers

There is a tolerable way to do this with a few list/dict comprehensions.

lst = [{"id": 14, "name": "cat14", "parent_id": 13, "path_info": [8, 10, 12, 13, 14]}, {"id": 15, "name": "cat15", "parent_id": 13, "path_info": [8, 10, 12, 13, 15]}]

master_dct = { d['id'] : d for d in lst}
for d in lst:
    d['subcats'] = [{field : master_dct[i][field] for field in ['id', 'name', 'parent_id']} \
        for i in d['path_info'] if i in master_dct]

import json
with open('out.json', 'w') as f:
    json.dump(lst, f)
like image 127
hilberts_drinking_problem Avatar answered Oct 05 '22 02:10

hilberts_drinking_problem