如何在Python中在循环中创建JSON数据?

如何在Python中在循环中创建JSON数据?,python,json,Python,Json,我尝试创建这样的循环,但它给了我错误 for prod in data: productId = prod['productId'] 错误: productId = prod['productId'] TypeError: string indices must be integers 如何创建产品: data = aliexpress.get_product_details(['productId', 'productUrl', 'discount', 'evaluateScore

我尝试创建这样的循环,但它给了我错误

for prod in data:
   productId = prod['productId']
错误:

productId = prod['productId']
TypeError: string indices must be integers

如何创建产品:

data = aliexpress.get_product_details(['productId', 'productUrl', 'discount', 'evaluateScore',
                                      'volume', 'packageType', 'lotNum', 'validTime', 'storeName', 'storeUrl', 'allImageUrls'], productId)
dmp = json.dumps(data)
for prod in dmp:
    print(prod)
    productId = prod['productId']
    productUrl = prod['productUrl']
    discount = prod['discount']
    evaluateScore = prod['evaluateScore']
    volume = prod['volume']
    packageType = prod['packageType']
    lotNum = prod['lotNum']
    validTime = prod['validTime']
    storeName = prod['storeName']
    storeUrl = prod['storeUrl']
    allImageUrls = prod['allImageUrls']

此问题源于尝试迭代字典的键:

for prod in data:
    print(prod)
这就回来了

 'volume'
 'productId'
 'evaluateScore'
 ...etc

当您询问
'volume'['productId']
时,Python会感到困惑-字符串支持整数索引,但该字符串
'productId'
对解释器来说毫无意义。解决方案是要么将该dict放入一个列表中,要么直接使用
prod['productId']

访问该元素。我想
数据
是一个字典,它将
prod
变成一个字符串。这就是将dict变成列表的方式吗?对于prod,data.items()中的值:productId=prod['productId']
prod=list(prod)
可以做到这一点,但我认为您误解了您遇到的问题-这几乎肯定不是您希望它做到的。尝试只访问
prod['productId']
而不是循环。我可以直接访问它,但我需要创建一个循环,以便在数据库中添加多个插入。看起来像是dmp中的prod的
这样做-在列表上迭代。如果您需要创建一个新的dict列表,您可以通过使用每个
prod
的部分创建dict来相当轻松地完成这项工作。
 'volume'
 'productId'
 'evaluateScore'
 ...etc