使用数组中的变量创建JSON对象

2024-09-25 00:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个数组创建一个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})

这给了我:

^{pr2}$

但我想得到:。。。这很重要吗?我对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
  }....
]

Tags: 对象json数组descriptionnullquantityitemcodeaccountcode
1条回答
网友
1楼 · 发布于 2024-09-25 00:27:41

您应该将其附加到列表中:

import json
line_items=[]
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
            }
    line_items.append(myjson3)
print(json.dumps(line_items))

相关问题 更多 >