我使用pymssql库查询结果,这里有一个例子:
(' 999001',' 4871C9DF-6E95-458B-B763-6BBBB6C75F5D',1,True,2,' EOI',' Dropped& #39;,无,无,4,假,假,' Enbloc',False,False,False,False,无,无,' USD',无,无,无,无,无,无,'投资',无,无,无,' JLL交易','独家授权','销售咨询' ,无,无,无,无,无,'韩国标准时间',无,无,无,无,无,无,无,无,无,1,无,真,'整体',假,假,假,假,假,假,无,' 1',无,无,无,无,无,无,十进制(' 0.05& #39;),' 100%',无,无,无,无,无,' Sqft',' USD',十进制(' 120000000.00'),' USD $ 1.220M',十进制(' 120000000.00'),' USD $ 1.220M',无,无,无,无,无,无,无,无,无,无,十进制(' 120000000.00'),十进制(' 120000000.00'),十进制(' 120000000.00' ;),十进制(&#3 9; 120000000.00'),'未公开',' Hubville Co Ltd'一个令人兴奋的投资机会 - 通往首尔的门户',无,无,无,无,'令人兴奋的投资机会 - 通往首尔的门户',无,无,datetime.datetime(2016,1,15,0,5,51,480000),datetime.datetime(2016, 12,7,5,6,52,633000),1,无)
但我发现有Decimal('120000000.00')
和datetime.datetime(2016, 1, 15, 0, 5, 51, 480000)
等值。我只想获得没有Decimal()和datetime.datetime()的原始值。我该如何实现呢?
这是我的代码:
def extract_opportunities(sql):
cursor.execute(sql)
opportunities = cursor.fetchall()
attributes = get_attributes_of_table(cursor)
availability_id_idx = attributes.index("availabilityid")
opportunity_dict = dict()
for idx, val in enumerate(opportunities):
opportunity_key = val[availability_id_idx]
opportunity_value = dict(zip(attributes, val))
opportunity_dict[opportunity_key] = opportunity_value
此函数的目的是构造具有属性和值对的JSON格式文件,如:
{'Price': '120000000.00'}
而不是
{'Price': Decimal('120000000.00')}
答案 0 :(得分:2)
您可以将from django.conf.urls import url
from views import SwaggerSchemaView
urlpatterns = [
url(r'^api/v1/docs/$', SwaggerSchemaView.as_view(), name='docs'),
]
函数传递给将default
转换为字符串的json.dumps
方法,如下所示:
Decimal
控制台输出是:
import datetime
from decimal import Decimal
import json
import pymssql
def json_dumps_default(obj):
# ref: http://stackoverflow.com/a/16957370/2144390
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, datetime.datetime):
return str(obj)
raise TypeError
conn = pymssql.connect(
host=r'localhost:49242',
database='myDb'
)
crsr = conn.cursor(as_dict=True)
sql = """\
SELECT
CONVERT(DECIMAL(18,4), 120000000) AS Price,
CONVERT(DATETIME, '2016-12-07 05:06:52.633') AS SaleDate
UNION ALL
SELECT
CONVERT(DECIMAL(18,4), 340000000) AS Price,
CONVERT(DATETIME, '2017-01-09 07:44:32.1') AS SaleDate
"""
crsr.execute(sql)
rows = crsr.fetchall()
print()
print("Rows as returned by pymssql:")
print(rows)
as_json = json.dumps(rows, default=json_dumps_default, sort_keys=False, indent=2)
print()
print("Rows as returned by json.dumps:")
print(as_json)
crsr.close()
conn.close()
请注意,对于Rows as returned by pymssql:
[{'Price': Decimal('120000000.0000'), 'SaleDate': datetime.datetime(2016, 12, 7, 5, 6, 52, 633000)}, {'Price': Decimal('340000000.0000'), 'SaleDate': datetime.datetime(2017, 1, 9, 7, 44, 32, 100000)}]
Rows as returned by json.dumps:
[
{
"Price": "120000000.0000",
"SaleDate": "2016-12-07 05:06:52.633000"
},
{
"Price": "340000000.0000",
"SaleDate": "2017-01-09 07:44:32.100000"
}
]
值,该函数可能会返回float(obj)
而不是str(obj)
,但可能会丢失精度。