玩蛇网提供最新Python编程技术信息以及Python资源下载!

python如何将无限分类结构的数据,转换成json格式数据。

id text pid

1 My Documents 0
2 photos 1
3 Friend 2
4 Wife 2
5 Company 2
6 Program Files 1
7 Intel 6
8 Java 6

数据库中是以上结构,如何写段代码生成如下结构的json数据?

[{

"id":1,
"text":"My Documents",
"children":[{
    "id":2,
    "text":"Photos",
    "children":[{
        "id":3,
        "text":"Friend"
    },{
        "id":4,
        "text":"Wife"
    },{
        "id":5,
        "text":"Company"
    }]
},{
    "id":6,
    "text":"Program Files",
    "children":[{
        "id":7,
        "text":"Intel"
    },{
        "id":8,
        "text":"Java",
    }]
}]

}]

import json
source=[
    {"name":"my document","id":1 , "parentid": 0 },
    {"name":"photos","id":2 , "parentid": 1 },
    {"name":"Friend","id":3 , "parentid": 2 },
    {"name":"Wife","id":4 , "parentid": 2 },
    {"name":"Company","id":5 , "parentid": 2 },
    {"name":"Program Files","id":6 , "parentid": 1 },
    {"name":"intel","id":7 , "parentid": 6 },
    {"name":"java","id":8 , "parentid": 6 },
]

def getChildren(id=0):
    sz=[]
    for obj in source:
        if obj["parentid"] ==id:
            sz.append({"id":obj["id"],"text":obj["name"],"children":getChildren(obj["id"])})
    return sz

print json.dumps(getChildren())
[
  {
    "text": "my document",
    "id": 1,
    "children": [
      {
        "text": "photos",
        "id": 2,
        "children": [
          {
            "text": "Friend",
            "id": 3,
            "children": [ ]
          },
          {
            "text": "Wife",
            "id": 4,
            "children ": [ ]
          },
          {
            "text": "Company",
            "id": 5,
            "children": [ ]
          }
        ]
      },
      {
        "text": "Program Files",
        "id": 6,
        "children": [
          {
            "text": "intel",
            "id": 7,
            "children": [ ]
          },
          {
            "text": "java",
            "id ": 8,
            "children": [ ]
          }
        ]
      }
    ]
  }
]

代码比较粗糙,性能不好,主要借鉴下思想吧

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd13854.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月19日 - 13时17分59秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules