Get Json from table using python

实验环境 Oracle 11.2.0.4 Python 2.7 + eclipse

Source Code:

#!/usr/bin/env python
# -*- coding: utf8 -*-
#Author Leo
#Date 2016.10.14

import cx_Oracle
import json
import os
import collections

SQL_TEXT = "select employee_id,first_name,last_name,email,job_id,salary,manager_id,department_id From hr.employees"

connection = cx_Oracle.connect('hr','hr','scan name:1521/service name')

cursor = connection.cursor()
cursor.execute(SQL_TEXT)
 
rows = cursor.fetchall()
 

rowarray_list = []
for row in rows:
    rowarray_list.append(row)
 
j = json.dumps(rowarray_list)
rowarrays_file = 'employees.js'
f = open(rowarrays_file,'w')
print >> f, j
 
objects_list = []
for row in rows:
    d = collections.OrderedDict()
    d['employee_id'] = row[0]
    d['first_name'] = row[1]
    d['last_name'] = row[2]
    d['email'] = row[3]
    d['job_id'] = row[4]
    d['salary'] = row[5]
    d['manager_id'] = row[6]
    d['department_id'] = row[7]
    objects_list.append(d)
 
j = json.dumps(objects_list)
objects_file = 'employees.js'
f = open(objects_file,'w')
print >> f, j
 
connection.close()

JSON Format Result:

[
   {
    "employee_id": 100, 
    "first_name": "Steven", 
    "last_name": "King", 
    "email": "SKING",
    "job_id": "AD_PRES", 
    "salary": 24000.0, 
    "manager_id": null, 
    "department_id": 90
   },
   {
    "employee_id": 101, 
    "first_name": "Neena", 
    "last_name": "Kochhar", 
    "email": "NKOCHHAR", 
    "job_id": "AD_VP", 
    "salary": 17000.0, 
    "manager_id": 100, 
    "department_id": 90
   } 
]
此条目发表在Python分类目录。将固定链接加入收藏夹。

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s