使用 Python 在 JSON 中查找字符串

新手上路,请多包涵

我目前得到一个很长的 JSON,我正试图通过 Python 2.7 从中挑选出 2 条信息。

JSON 大致如下所示:

 {
  'device': [
    {
      'serial': '00000000762c1d3c',
      'registered_id': '019'
    },
    {
      'serial': '000000003ad192f2',
      'registered_id': '045'
    },
    {
      'serial': '000000004c9898aa',
      'registered_id': '027'
    }
  ],
}

在此 JSON 中,我正在寻找可能与 JSON 中的序列匹配的特定序列。如果是这样,它也应该打印出 registered_id。

我试过使用一个简单的脚本,即使没有 registered_id 但我一无所获。:

 if '00000000762c1d3c' not in data['device']:
        print 'not there'
else:
        print 'there'

感谢您的建议!

原文由 user5740843 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 542
2 个回答

date['device'] 包含一个对象列表,所以你应该这样对待它并迭代它们:

 for element in data['device']:
    if element['serial'] == '00000000762c1d3c':
        print 'there'
        print element['registered_id']
        break
else:
    print 'not there'

这是使用某种鲜为人知的 for-else 构造: https ://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on -循环

原文由 DeepSpace 发布,翻译遵循 CC BY-SA 3.0 许可协议

首先,您的输入不是 json。 Json 使用双引号。但是假设你成功地用 json 加载 了它,它现在是一个字典,叫做 d

然后,您可以扫描 --- 的所有子字典 d 并测试 serial 针对您的值的键,找到时停止使用 any 和理解生成器:–

 print(any(sd['serial']=='00000000762c1d3c' for sd in d['device']))

返回 True 如果找到序列 False 否则。

原文由 Jean-François Fabre 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题