【发布时间】:2016-04-02 01:51:48
【问题描述】:
我想创建一个带有数组的 JSON 对象,但我似乎无法解决问题。我遇到的问题是它只将最后一个索引值分配给我的变量。有人可以告诉我如何将循环中产生的所有内容分配给一个变量吗?
...所以我已经能够通过我的 json 对象循环我的数组,但是在细节方面遇到了麻烦。
这是我的代码:
lineitems = []
for q in ItemDetails:
myItemName = q[0]
myQuantity = q[1]
myUnitAmount = float(q[2])
myItemCode = str(q[3])
myjson3 = {
'ItemCode': myItemCode,
'Description': myItemName,
'UnitAmount': myUnitAmount * myDiscount,
'Quantity': myQuantity,
'AccountCode': myAccountCode,
'TaxType': myTaxType
},
lineitems.append(myjson3)
print({'LineItems': myjson3})
这给了我:
"LineItems": [
[
{
"AccountCode": null,
"Description": "Banana Parfait",
"UnitAmount": 0.0,
"TaxType": null,
"ItemCode": "44",
"Quantity": 2.0
}
],
[
{
"AccountCode": null,
"Description": "Blackened Tofu",
"UnitAmount": 5.95,
"TaxType": null,
"ItemCode": "42",
"Quantity": 1.0
}
]....]
但我想:……这很重要吗?我对 JSON 对象很陌生
"LineItems": [
{
"AccountCode": null,
"Description": "Banana Parfait",
"UnitAmount": 0.0,
"TaxType": null,
"ItemCode": "44",
"Quantity": 2.0
}
,
{
"AccountCode": null,
"Description": "Blackened Tofu",
"UnitAmount": 5.95,
"TaxType": null,
"ItemCode": "42",
"Quantity": 1.0
}....
]
【问题讨论】:
-
如果我正确理解了这个问题,我想您可能只想在该打印语句上加标签,以便它在 for 循环的每次迭代中执行。
标签: python arrays json python-3.x for-loop