是否可以根据第一列值将pymssql查询转换为json?

时间:2019-10-04 17:39:01

标签: python json pymssql

我正在尝试将pymssql查询转换为json,其中第一列“值”将为“键”,相应的列将为“键:值”的列表。

我尝试使用jsondumps,但收到“光标不可JSON可序列化”错误:

    `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"
      }
   ]
}```

1 个答案:

答案 0 :(得分:0)

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)
  • ddefaultdict,带有list参数,因此,如果您添加不在d中的键,则在第一次分配时将创建list作为值时间。