【发布时间】:2020-08-28 20:06:48
【问题描述】:
我从以下请求中得到字符串格式的 json 响应:
results = requests.request("POST", url, data=json.dumps(payload), headers=header).json()['product']
示例输出:
print(results) - 对象类型 =
[
{
'id': '123456',
'product': 'XYZ',
'exp_date': '03/01/2020',
'amount': '30.5',
'qty': '1'
},
{
'id': '789012',
'product': 'ABC',
'exp_date': '04/15/2020',
'amount': '22.57',
'qty': '3'
},
{
'id': '56789',
'product': 'AAA',
'exp_date': '03/29/2020',
'amount': '',
'qty': ' '
}
]
需要先将所有这些字段转换为特定的数据类型,然后作为文档插入到MongoDB中。
- exp_date 到 日期/时间
- 金额为 float()
- 数量为 int()
进行数据类型转换的有效方法是什么?
正在考虑是否有可能像下面这样,还需要知道是否有任何空、空或空白字符串值,那么在数据类型转换期间如何将其替换为一些默认值?
new_result = []
for i in enumerate(results):
i[exp_date] = datetime.strptime(i[exp_date],'%m/%d%Y').replace(hour=0, minute=0, second=0, microsecond=0) #check for empty/null/blank values and replace with default date
new_result.append(i[exp_date])
for i in enumerate(results):
i[amount] = float(i[amount]) #check for empty/null/blank values and replace with 0.00
new_result.append(i[amount])
for i in enumerate(results):
i[qty] = int(i[qty]) #check for empty/null/blank values and replace with 0
new_result.append(i[qty])
db.collection.insert_many(new_result)
新列表输出应如下所示:print(new_result)
[
{
"id": "123456",
"product": "XYZ",
"exp_date": 2020-03-01 00:00:00,
"amount": 30.5,
"qty": 1
},
{
"id": "789012",
"product": "ABC",
"exp_date": 2020-04-15 00:00:00,
"amount": 22.57,
"qty": 3
},
{
"id": "56789",
"product": "AAA",
"exp_date": 2020-03-29 00:00:00,
"amount": 0.0,
"qty": 0
}
]
【问题讨论】:
标签: python mongodb type-conversion pymongo string-to-datetime