簡體   English   中英

如何從 json 文件中獲取密鑰對值?

[英]How to get the Key Pair value from a json file?

數據 = "[{"id":"abc, "content":"Bye", "child": [{"id":"dsd", "parent id": "abc", "content": "dds" }]},{“id”:xcv,“內容”:“你好”}]”

   with open("data.json","w") as f:
        json.dump(data, f)

    # reads it back
    with open("data.json","r") as f:
        parsed_json = json.load(f)

    for e in parsed_json:
        print (e["content"])

我想提取再見和你好,但我偶然發現了這個錯誤。 想知道如何循環

TypeError                                 Traceback (most recent call last)
<ipython-input-2-1aa8088c77a7> in <module>
     46 
     47     for e in parsed_json:
---> 48         print (e["content"])
     49 
     50 

TypeError: string indices must be integer

不要使用json.dump將字符串寫入文件。 使用它將數據結構(列表、字典等)寫入文件。

因此,不要將data變量的原始值放在引號內。

此外,您缺少數據中的一些引號( abc缺少結束引號,而xcv缺少兩個引號)。

import json

data = [{"id":"abc", "content":"Bye", "child": [{"id":"dsd", "parent id":"abc", "content":"dds"}]}, 
        {"id":"xcv", "content":"hello"}]

with open("data.json","w") as f:
        json.dump(data, f)

# reads it back
with open("data.json","r") as f:
    parsed_json = json.load(f)

for e in parsed_json:
    print (e["content"])

暫無
暫無

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

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