【问题标题】:How to find the index of an object key in JSON Python [closed]如何在 JSON Python 中查找对象键的索引 [关闭]
【发布时间】:2022-11-11 06:00:16
【问题描述】:

我有以下 JSON 文件

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

并且我想找到例如带有键“cya”的响应,在这种情况下是“再见”或标签,即“再见”。 在“sup”这个词中,它会是响应“Hi”。

【问题讨论】:

  • 没有密钥cya。它是words 属性中的数组元素。
  • 你不应该要求别人为你做你的工作,你应该自己去想办法。在您尝试弄清楚之后,如果您仍然无法做到,请发布您正在尝试的内容,然后询问。

标签: python json


【解决方案1】:

我假设你想找到你在数组中定义的整个对象结构,并在单词数组中的任何单词匹配时返回它。 您可以使用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)

请注意,您也可以将 jsonObj 作为函数的参数,然后您可以将其称为 findByWord(someJsonObj, someWordToFind)

【讨论】:

  • 嗨,我实际上使用的是 python 而不是 javascript,无论如何感谢您的回答。
  • 哇,我很抱歉,我已经用 python 更新了答案:)
  • 天哪,成功了,非常感谢!!我真的花时间在这但没有找到任何东西,当然,我应该使用 for 循环
猜你喜欢
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-19
  • 2018-10-12
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多