Home > database >  How to find the index of an object key in JSON Python
How to find the index of an object key in JSON Python

Time:01-26

I have the following JSON file

[
{
    "tag": "greetings",
    "words": ["hey", "hi", "sup"],
    "response": "Hi"
},
{
    "tag": "goodbye",
    "words": ["bye", "cya"],
    "response": "See you"
}
]

and I want to find for example the response that is placed with the key "cya", in this case "See you", or the tag, that would be "goodbye". In the word "sup", it would be response "Hi".

CodePudding user response:

I am assuming you want to find the entire object structure you have defined in the array, and return it on any word match in the words array. You can do this using find()

json_obj = [{
    "tag": "greetings",
    "words": ["hey", "hi", "sup"],
    "response": "Hi"
}, {
    "tag": "goodbye",
    "words": ["bye", "cya"],
    "response": "See you"
}]

def find_by_word(findWord):
    for obj in json_obj:
        if "cya" in obj["words"]:
            return obj

result = find_by_word("cya")
print(result)

Note that you could also give the jsonObj as a parameter of the function, and then you could call it, per example, as findByWord(someJsonObj, someWordToFind)

  •  Tags:  
  • Related