以下是json檔擷取出片段,
若想透過輸入enUS的值,
回傳給我他的zhTW,
是否有快速的方法可以操作,
小弟目前的想法是透過迴圈,
是否有json的操作方式,小弟沒想到的
謝謝
example:
[input]→software
[output]→軟體
[
{
"id": 1930,
"enUS": "software",
"zhTW": "軟體",
"zhCN": "软件"
},
{
"id": 1931,
"enUS": "Flash drive",
"zhTW": "隨身碟",
"zhCN": "U盘"
},
{
"id": 1932,
"enUS": "Mouse",
"zhTW": "滑鼠",
"zhCN": "鼠标"
}
]
data = [
{
"id": 1930,
"enUS": "software",
"zhTW": "軟體",
"zhCN": "软件"
},
{
"id": 1931,
"enUS": "Flash drive",
"zhTW": "隨身碟",
"zhCN": "U盘"
},
{
"id": 1932,
"enUS": "Mouse",
"zhTW": "滑鼠",
"zhCN": "鼠标"
}
]
def search(input, data):
ans = list(filter(lambda x:x["enUS"]==input,data))
ans = ans[0]["zhTW"]
return ans
def search_for(input, data):
for i in data:
if i["enUS"] == input:
ans = i["zhTW"]
return ans
print(search("software", data))
print(search_for("software", data))
參考資料
Find a value in JSON using Python
假定有 json 數據多條記錄,如何根據 KEY 的值返回一條記錄?