【问题标题】:Iterating through JSON to find if a defined object exists遍历 JSON 以查找定义的对象是否存在
【发布时间】:2011-09-04 02:40:00
【问题描述】:

感谢您的帮助。我在 python 中工作。

我正在请求一个 json 页面并加载它。

fooList = json.load(urllib.urlopen(
    "https://path.to.json.com/request?"))

看起来像这样:

{
   "data": [
      {
         "foo": "2323582"
      },
      {
         "foo": "32689023"
      },
      {
         "foo": "125815512"
      },
      {
         "foo": "1252015"
      },
      {
         "foo": "12518505"
      },
      {
         "foo": "109251907590"
      },
      {
         "foo": "2158019258"
      },
      {
         "foo": "2198059018"
      }
   ]
}

我有一个定义的对象

obj = 1252015

然后我想遍历该列表,并给出一个关于obj 是否存在于fooList 中的布尔答案

findObj = 'This is where I need help'

预期结果:

print findObj
True

【问题讨论】:

    标签: python arrays json find loops


    【解决方案1】:
    >>> print any(x['foo']=='1252015' for x in yourJson['data'])
    True
    

    any 接受任何返回布尔值的生成器g=<generator>,并等效于g[0] or g[1] or g[2] or ... or g[N]。当然,如果您不只是想搜索yourJson['data'],那就另当别论了,您需要定义一个递归函数。

    【讨论】:

    • 小而重要的细节:foo 的值是一个字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多