【问题标题】:Kafka Producer TypeError: list indices must be integers or slices, not dictKafka Producer TypeError:列表索引必须是整数或切片,而不是字典
【发布时间】:2020-06-17 22:58:58
【问题描述】:

我正在将 json 对象从 kafka 生产者发送到 kafka 消费者,但我遇到了错误:

TypeError: list indices must be integers or slices, not dict.

以下是我的 kafka 生产者代码:

jsonFilePath = "data.json"

data = None
with open(jsonFilePath) as f:
  data = json.load(f)

print(type(data))


print(len(data))
count = 0
for record in data:
    # print(str(data[record]))
    # print(data[record])
    producer.send('testTopic', value=data[record])
    count = count + 1

我的 json 对象看起来像:

 {
    "Order Number": "CA-2014-103800",
    "Order Status": "Completed",
    "Order Date": "03/01/2014",
    "First Name (Billing)": "Saima",
    "Last Name (Billing)": "Nasir",
    "Company (Billing)": "",
    "Address 1&2 (Billing)": "",
    "City (Billing)": "",
    "State Code (Billing)": "PB",
    "Postcode (Billing)": 54810,
    "Country Code (Billing)": "PK",
    "Email (Billing)": "",
    "First Name (Shipping)": "Saima",
    "Last Name (Shipping)": "Nasir",
    "Address 1&2 (Shipping)": "",
    "City (Shipping)": "Lahore",
    "State Code (Shipping)": "PB",
    "Postcode (Shipping)": 54810,
    "Country Code (Shipping)": "PK",
    "Shipping Method Title": "Free shipping",
    "Payment Method Title": "Cash on delivery",
    "Cart Discount Amount": 0,
    "Order Subtotal Amount": 0,
    "Order Shipping Amount": 0,
    "Order Refund Amount": 0,
    "Order Total Amount": 16.448,
    "Order Total Tax Amount": 0,
    "Category": "Kids",
    "Item # #1": 1,
    "SKU #1": "",
    "Item Name #1": "Ladies Shoes - Navy, 40",
    "Quantity #1": 2,
    "Item Cost #1": 0,
    "Coupon Code": "",
    "Discount Amount": 0.2,
    "Discount Amount Tax": "",
    "Profit": 5.5512
  }

【问题讨论】:

标签: python json apache-kafka kafka-producer-api


【解决方案1】:

在您的 for 循环中,record 不是索引,而是实际值。


因此,而不是

for record in data:
    producer.send('testTopic', value=data[record])

尝试以下方法:

for record in data:
    producer.send('testTopic', value=record])

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2016-09-19
    • 2020-07-11
    • 2022-10-04
    • 2016-09-16
    • 1970-01-01
    • 2019-07-04
    • 2015-12-09
    相关资源
    最近更新 更多