簡體   English   中英

我想在 python 中打印“'標識符':'OPTSTKHDFC25-08-2022PE1660.00'”。 在下面嘗試,給出錯誤 TypeError: string indices must be integers

[英]I want to print "'identifier': 'OPTSTKHDFC25-08-2022PE1660.00'" in python. Tried below, gives error TypeError: string indices must be integers

在此處輸入圖像描述 從 nsepython 導入 *

導入 pandas 作為 pd

進口 json

位置 = nse_optionchain_scrapper ('HDFC')

json_decode = json.dumps(positions,indent = 4, sort_keys=True,separators =(".", "= "))

打印(json_decode['data'][0]['identifier'])

問題是你錯過了一個步驟。

identifierPE 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM