从MySQL DB中的多个表创建Json文件

时间:2015-12-29 05:48:55

标签: mysql json python-2.7 unix amazon-web-services

我在MySQL数据库中有2个不同的表(Person和sport)。我想以下列格式从这两个表创建一个json文件。 Person表具有first_name,middle_name和last_name列,sport表具有sport_name和league_name列。从逻辑上讲,每个人可能有多个运动项目。请帮帮我

“score”: {
     “ps”:{
        “person”:{
            “first_name”: "fName1"
            “middle_name”: "MName1"
            “last_name”: "Lname1"               
            "sports":{
                "sport":{
                    “sport_name”: "sport1"
                    “league_name”: "legue1"
                }
                "sport":{
                    “sport_name”: "sport2"  
                    “league_name”: "legue2"
                }
             }
        }
        “person”:{
            .......
        }
    }
}

我绑了以下代码并回答但是我希望将这项运动视为子阵列 我尝试了以下代码。我希望运动成为一个人的阵容。

#!/usr/bin/env python
import MySQLdb
import json
import collections
from collections import defaultdict 
class Dict(defaultdict):
    def __init__(self):
        defaultdict.__init__(self, Dict)
    def __repr__(self):
        return dict.__repr__(self) 

db = MySQLdb.connect("Server","userName","pawd","dbName" )

# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT person_id,first_name,last_name,gender FROM scorefoliodev1.person "
cursor.execute(sql)

rows = cursor.fetchall()
objects_list = []
for row in rows:
    d = Dict()
    d["Person"]['person_id'] = row[0]
    d["Person"]['first_name'] = row[1]
    d["Person"]['last_name'] = row[2]
    d["Person"]['gender'] = row[3]
    objects_list.append(d)

j = json.dumps(objects_list, indent=4)
print j
objects_file = 'person_info55.js'
f = open(objects_file,'w')
print >> f,j 
db.close()

答案

[
    {
        "Person": {
            "person_id": 111, 
            "gender": "Male", 
            "first_name": "FName1", 
            "last_name": "LName"
        }
    }, 
    {
        "Person": {
            "person_id": 112, 
            "gender": "Male", 
            "first_name": "fname2", 
            "last_name": "lName2"
        }
    }
]

2 个答案:

答案 0 :(得分:0)

json格式允许您定义数组。你可以这样做:

"sports":[
   {
      "sport_name": "sport1",
      "league_name": "legue1"
   },
   {
      "sport_name": "sport2",
      "league_name": "legue2"
   }
]

答案 1 :(得分:0)

  

我的问题是子数组,运动是人数组的子数组。我是新的   到Python并且不知道如何创建列表来生成json文件   与子数组

你说:使用" person_id" 相关的人和运动表。因此,我们可以为人们创建一个包含体育运动的字典。假设e。 G。 SELECT person_id,sport_name,league_name FROM sport生成rows

   [[111, "sport1", "legue1"],
    [112, "sport2", "legue2"],
    [111, "sport3", "legue3"]]

然后我们可以做

sports = {}
for row in rows:
    sport = { "sport_name": row[1], "league_name": row[2] }
    if not row[0] in sports: sports[row[0]] = []
    sports[row[0]].append(sport)

sports会产生

{
    "112": [ { "league_name": "legue2", "sport_name": "sport2" } ], 
    "111": [ { "league_name": "legue1", "sport_name": "sport1" }, 
             { "league_name": "legue3", "sport_name": "sport3" } ]
}

现在我们有子数组,我们可以简单地将其插入到您已经拥有的人objects_list中:

for person in objects_list:
    person["Person"]['sports'] = sports[person["Person"]['person_id']]