简体   繁体   中英

Is it possible to search a json object key based on another key in python?

Total json noob here. I have the json data as follows:

response: [{'id': '1', 'name': 'TimeCheck1'},{'id': '2', 'name': 'TimeCheck2'}]

I need to display the value of 'id' as 1, based on the 'name' 'Timecheck1'.

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")

I was trying the above code to get somewhere, but I keep facing the error 'string indices must be integers'

It seems like you've already got the response decoded. json.dumps is simply converting that data back to a string. This function will look up the name and return the id of the item if it is found or None if it is not.

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 returns a string.

>>> 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``.
...

Perhaps you meant to do

>>> 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
>>> 

This question is either about json or its not. I'm guessing its not. So lets proceed on that basis.

Your response variable seems to be a list so we can iterate over that:

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")

You could do this,

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM