我想讀一個嵌套的json,比如
"Experiment"{
"rats"{
"animal":[1,2,3,4]
}
"dogs"{
"animal":[1,2,3,4]
}
}
(我希望我正確設定了所有括號)
現在我想讓它可變以在 Dogs 或 rats 中讀取(別擔心,我實際上并沒有在動物身上進行實驗 :-))
所以而不是
conf=pd.read_json(filepath)
animal=conf[Experiment][dogs][1]
我想用
conf=pd.read_json(filepath)
a="dogs"
b="rats"
animal=conf[Experiment]a[1]
有人可以提示如何做到這一點嗎?謝謝
uj5u.com熱心網友回復:
只要您清理語法,您基本上就可以在問題中找到答案。如果您將 json 更改為此:
{
"Experiment": {
"dogs": {
"animal": [ 1, 2, 3, 4 ]
},
"rats": {
"animal": [ 1, 2, 3, 4 ]
}
}
}
(注意“狗”之后的逗號,環繞{}
并:
分隔鍵和值)您可以通過以下方式進行第一種方式:
import pandas as pd
conf = pd.read_json("animals.json")
animal = conf["Experiment"]["dogs"]["animal"]
或者你想要的方式:
import pandas as pd
a = "dogs"
conf = pd.read_json("animals.json")
animal = conf["Experiment"][a]["animal"]
我假設您要獲取的是 array [1,2,3,4]
,但是如果您愿意,請從上方"animal": [1,2,3,4]
離開。["animal"]
您的問題缺少圍繞鍵的引號,因此這可能是您的問題。您可以輕松地將變數設定為您要查找的鍵的字串(“dog”)并使用它。您還嘗試使用 索引dogs
,[1]
但dogs
不是陣列,所以也許您打算放置[]
而"animal": [ 1, 2, 3, 4 ]
不是{}
?
此外,你不一定需要使用pandas
(除非你做的比這里提到的更多)。你也可以這樣做:
import json
a = "dogs"
f = open("animals.json")
conf = json.load(f)
animal = conf["Experiment"][a]["animal"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494939.html