【问题标题】:Python: TypeError: string indices must be integers [closed]Python:TypeError:字符串索引必须是整数[关闭]
【发布时间】:2020-02-27 13:48:28
【问题描述】:

这是在这里发布了很多时间的类似问题,但我无法理解它。

import json

str2 ="""[{'cta': [], 'ctr': 2880509, 'client_id': '229132', 'exchange': 'NSE_EQ', 'token': '3063', 'product': 'CO', 'order_type': 'M', 'duration': 'DAY', 'price': '0', 'trigger_price': '149.10', 'quantity': 1, 'disclosed_quantity': 0, 'side': 'S', 'avg_price': '148.10', 'traded_quantity': 1, 'pending_quantity': 0, 'message': '', 'exchange_order_id': '1300000006005800', 'syom_order_id': 'NA', 'order_number': '191101000336718', 'timestamp': '01/11/2019,12:19:45', 'exchange_timestamp': '01-Nov-2019 12:19:45', 'status': 'complete', 'time_in_micro': '1572590985928000', 'is_amo': False, 'order_complexity': 'CO', 'request_id': '1', 'valid_date': '--', 'tag': 'JWEB|TB1', 'comments': 'PLACE ORDER :: 229132|NSE_EQ|3063|EQ|I|0|1|S|CO|WEB|IP-172-31-4-125|1572590985897', 'fill_id': '', 'original_message': '', '_amo': False}]"""
str2 = (json.dumps(str2))
print(str2)
print(str2['client_id'])

为什么这不起作用?它说 -

print(str2['client_id'])
TypeError: string indices must be integers

请注意,str2 是从某个地方输出的,我的目标是获取 client_id 或任何其他变量。

那么我正在寻找的是可能的解析方式是什么?

【问题讨论】:

    标签: python arrays json


    【解决方案1】:

    这里有多个问题。你似乎没有考虑清楚。

    你从一个字符串开始。在一个字符串上调用json.dumps 只会给你另一个字符串。但是你也不能在原始字符串上调用json.loads,因为它不是JSON;它似乎是 Python 对象的字符串表示形式。

    但是,即使您已经正确解析了它,它仍然 不起作用,因为它代表一个列表 字典,而不是单个字典。

    这似乎不太可能是您的外部系统的实际输出。如果您需要进一步的帮助,您需要准确解释您是如何获得该字符串的。

    【讨论】:

      猜你喜欢
      • 2022-08-02
      • 1970-01-01
      • 2014-02-15
      • 2021-05-04
      • 1970-01-01
      • 2020-08-09
      • 2020-08-28
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多