簡體   English   中英

如何從 Python 中的 JSON 中刪除額外的方括號?

[英]How do I remove an extra square bracket from JSON in Python?

我有以下形式的 JSON:

{"blah":
 [
   [
     {"first":
     {"something":"that","something":"else","another":"thing","key":"value"}...[etc.]
     }
   ]
 ]
}

我試圖在 Python 中解析。 我已經導入了 json (或 simplejson,具體取決於您使用的 Python 的版本)並且一切順利,直到我到達這個塊:

for result in page['blah']:
  that = result['first']
  a_list.append(that)

這會引發錯誤“TypeError:列表索引必須是整數,而不是 str”。

我很確定這個錯誤是由於額外的一對方括號使 JSON 內部看起來像一個列表。

假設是這種情況,我的問題是,如何刪除它並且仍然有有效的 JSON 解析為字典?

歡迎其他解決方法。 如果我需要提供更多信息,請告訴我。 謝謝!

(添加了缺少的大括號並更改了一些令人困惑的術語——我試圖在飛行中提出通用術語,對於任何混淆感到抱歉。)

如果總是有一組“額外”的數組括號:

for result in page['blah']:
    that = result[0]['this']
    list.append(that)

無需從 JSON 字符串中移除括號。 我認為確保只刪除權利是不值得的。 只需找出訪問所需值的正確方法即可。

“額外的”括號不是唯一的問題。 this是 object 的屬性,它是first的值。 所以要訪問this ,你必須寫

that = result[0]['first']['this']

這是否總是有效取決於遺漏的 JSON 數據。

首先,您是對的 - 您的錯誤與 Python 數據類型和 JSON output 的錯誤使用有關。

其次,在創建變量時不要使用list和所有其他 Python 保留字。

最后,如果您只是想獲取'this'內鍵的所有結果,可以嘗試使用以下代碼:

data = {"blah":
 [
   [
     {"first":
     {"this":"that",
     "something":"else","another":"thing","key":"value"}}
   ]
 ]
}
outres = []
for k,v in data.items():#iterate over top dictionary('blah',....)
    for sv in v: # iterate through first list
        for tv in sv: # iterate through second list
            for fk,fv in tv.iteritems(): # iterate through each dicionary from second list
                if 'this' in fv:
                    outres.append(fv['this'])
print outres

請注意,我的示例基於您的數據示例 - 因此,如果您的數據結構中有任何其他級別,或者應該應用任何其他規則,則應修改代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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