使用Python在JSON中查找字符串

2024-04-28 15:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在得到了一个很长的JSON,我正试图通过Python 2.7从中挑选出两条信息。

JSON大致如下:

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

在这个JSON中,我正在寻找一个特定的序列号,它可能与JSON中的序列号匹配。如果是的话,它也应该打印出注册的身份证。

我试过使用一个简单的脚本,即使没有注册的id,但我还是一无所获

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

谢谢你的建议!


Tags: in脚本信息idjsonifdeviceserial
3条回答

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

然后,您可以扫描d的所有子指令,并根据您的值测试serial键,在使用any和生成器理解找到时停止:

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

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

也许这能帮你:

if [x for x in data['device'] if x.get('serial')=='00000000762c1d3c']:
  print "IN"
else:
  print "NOT"

可以使用Python: List Comprehensions以非常自然、简单的方式构造列表,就像数学家用来做的那样。

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-loops

相关问题 更多 >