有没有办法根据第一列值将 pymssql 查询转换为 json?

Is there way to convert pymssql query to json based on first column values?

我正在尝试将 pymssql 查询转换为 json,其中第一列 "value" 将是 "key",相应的列将是 "key:value".[=14= 的列表]

我曾尝试使用 json 转储,但出现 "Cursor is not JSON serializable" 错误:

    `conn = pymssql.connect(server, port, db)
     cursor = conn.cursor('select u_business_service_display_value as Business, name, host_name as hostname, install_status, ip_address, used_for from cmdb_ci_server where u_patching_director_display_value = <Name> AND install_status <> "Retired" AND install_status <> "Pending Retirement" order by Business, hostname')
     for row in cursor:
         print("Business=%s, Name=%s, Hostname=%s, install_status=%s, ip_address=%s, used_for=%s" % (row['Business'], row['name'], row['hostname'], row['install_status'], row['ip_address'], row['used_for']))
     print json.dumps(results, indent=1)
     conn.close()`

输出是

- Business=AAA, Name=Value, Hostname=vaule, install_status=Retired, ip_address=<ip>, used_for=None
- Business=AAA, Name=Value, Hostname=vaule, install_status=Retired, ip_address=<ip>, used_for=None
- Business=BBB, Name=Value, Hostname=vaule, install_status=Installed, ip_address=<ip>, used_for=Prod
- Business=BBB, Name=Value, Hostname=vaule, install_status=Installed, ip_address=<ip>, used_for=Prod

预期输出

{
        "AAA":[
        { 
        "Hostname":"Value",
        "install_status":"Retired",
        "ip_address":"<ip>",
        "used_for":"None"
        },
        {
         "Hostname":"Value",
         "install_status":"Retired",
         "ip_address":"<ip>",
         "used_for":"None"
      }
   ],
   "BBB":[ 
      { 
         "Hostname":"Value",
         "install_status":"Installed",
         "ip_address":"<ip>",
         "used_for":"Prod"
      },
      { 
         "Hostname":"Value",
         "install_status":"Installed",
         "ip_address":"<ip>",
         "used_for":"Prod"
      }
   ]
}```
from collections import defaultdict
import json
d = defaultdict(list)
for row in cursor:
    values = dict()
    values['name'] = row['name']
    values['hostname'] = row['hostname']
    values['install_status'] = row['install_status']
    values['ip_address'] = row['ip_address'] 
    values['used_for'] = row['used_for]
    d[row['Business']].append(values)

with open('result.json', 'w') as fp:
    json.dump(d, fp)
  • d 是带有 list 参数的 defaultdict 因此,如果您添加不在 d 中的键,它将创建 list 作为值第一次分配。