简体   繁体   中英

How to assign keys to JSON objects?

I have a script which takes data in a SQL Server database and parses it into a key:value pair JSON. I would like to give the three items in the JSON dictionary; one key, such as "ServiceRequest" at the highest level. So that my output would read as:

{
    "ServiceRequest": [
        {
            "SRNUMBER": "1-3580171",
            "FirstName": "Myla",
            "LastName": "Threeoneone"
        }
    ]
}

Program:

import pyodbc
import json
import collections
import requests

import urllib

connstr = 'DRIVER={SQL Server};SERVER=ServerName;DATABASE=DataBase; UID=UID;PWD=PWD'
conn = pyodbc.connect(connstr)
cursor = conn.cursor()

cursor.execute("""
            SELECT SRNUMBER, FirstName, LastName
 FROM MYLA311 """)

rows = cursor.fetchall()

# Convert query to row arrays

rowarray_list = []
for row in rows:
    t = (row.SRNUMBER)
    rowarray_list.append(t)

j = json.dumps(rowarray_list)
rowarrays_file = 'student_rowarrays.js'
f = open(rowarrays_file,'w')

# Convert query to objects of key-value pairs

objects_list = []
for row in rows:
     d = collections.OrderedDict()
     d['SRNUMBER']= row.SRNUMBER
     d['FirstName']= row.FirstName
     d['LastName']= row.LastName

objects_list.append(d)

j = json.dumps(objects_list)
objects_file = 'C:\Users\Administrator\Desktop\JSONOutput.txt'
f = open(objects_file,'w')
print >> f, j

print j

conn.close()

Actual Output:

[
    {
        "SRNUMBER": "1-3580171",
        "FirstName": "Myla",
        "LastName": "Threeoneone"
    }
]

JSON and Python dictionaries are very similar.

Your desired output is already valid Python:

{
    "ServiceRequest": [
        {
            "SRNUMBER": "1-3580171",
            "FirstName": "Myla",
            "LastName": "Threeoneone"
        }
    ]
}

So all you need to do, is wrap your objects list in a Python dictionary:

output = {
    'ServiceRequest': object_list
}

# then dump it
json.dumps(output)
# ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM