[英]I want to print "'identifier': 'OPTSTKHDFC25-08-2022PE1660.00'" in python. Tried below, gives error TypeError: string indices must be integers
問題是你錯過了一個步驟。
identifier
在PE
object 內
這應該有效:
print(json_decode['data'][0]['PE']['identifier'])
print(json_decode['filtered']['data'][0]['PE']['identifier'])
json_decode = json.dumps(positions,indent = 4, sort_keys=True,separators =(".", "= "))
您不能構建 JSON 字符串(這是json.dumps
所做的),然后嘗試訪問部分結果,就好像它是原始數據結構一樣。 您的json_decode
只是一個字符串,而不是字典; 就 Python 而言,除了組成它的單個字符之外,它沒有其他結構。
如果要訪問部分數據,直接使用positions
即可:
print(positions['data'][0]['identifier'])
如果您願意,您可以將該位編碼為 JSON:
print(json.dumps(positions['data'][0]['identifier'])
但在這種情況下,這可能只是一個帶引號的字符串。
所以我不確定你的目標是什么。 如果您想打印 JSON 版本的positions
,很好,只需打印出來。 但 JSON 形式僅用於輸入和 output; 它不適合在您的 Python 代碼中亂搞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.