[英]Is it possible to search a json object key based on another key in python?
這里有 json 菜鳥。 我的json數據如下:
響應: [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]
我需要根據'name'
“Timecheck1”將'id'
的值顯示為 1。
response= [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]
# change the JSON string into a JSON object
jsonObject = json.dumps(response)
a ='TimeCheck1'
if a in jsonObject:
#print(jsonObject[a])
print(json.dumps(jsonObject[a]))
else:
print("no")
我正在嘗試上面的代碼到達某個地方,但我一直面臨錯誤'string indices must be integers'
您似乎已經對響應進行了解碼。 json.dumps
只是將該數據轉換回字符串。 此函數將查找名稱並在找到時返回項目的 id,否則返回 None。
def find_id_by_name(response, name):
for item in response:
if item["name"] == name:
return item["id"]
else: # not found
return None
id = find_id_by_name(response, name)
if id is None:
print("Not found")
json.dumps返回一個字符串。
>>> import json
>>> help(json.dumps)
Help on function dumps in module json:
dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Serialize ``obj`` to a JSON formatted ``str``.
...
也許你打算做
>>> response= [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]
>>> a = 'TimeCheck1'
>>> for d in response:
... if a == d['name']:
... print(json.dumps(d))
... else:
... print("no")
...
{"id": "1", "name": "TimeCheck1"}
no
>>>
這個問題要么是關於json
要么不是。 我猜不是。 所以讓我們在此基礎上繼續。
您的response
變量似乎是一個列表,因此我們可以對其進行迭代:
response= [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]
target ='TimeCheck1'
for item in response:
if item['name'] == target:
print(f'Found: "{target}" with id:{item["id"])')
break
else:
print("no")
你可以這樣做,
response= [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]
# change the JSON string into a JSON object
jsonObject = json.dumps(response)
a = 'TimeCheck1'
for x in range(len(jsonObject)):
if jsonObject[x]['name'] == a
print(jsonObject[x]['id'])
else:
print("no")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.