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

Question:

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

Asked By: Neo

||

Answers:

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

Answered By: Jurriaan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.