【问题标题】:Create JSON object with variables from an array使用数组中的变量创建 JSON 对象
【发布时间】: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


【解决方案1】:

你应该把它附加到一个列表中:

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))

【讨论】:

  • 谢谢,这很有帮助!
猜你喜欢
  • 2012-10-10
  • 2019-12-30
  • 2012-04-01
  • 2020-02-16
  • 2018-09-10
  • 2013-08-28
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多