从Json输出(urllib2)检查字典

问题描述 投票:1回答:3

我正在尝试使用urllib2从json输出中提取特定数据。从下面的代码和输出中,我试图提取特定的值,但是我没有做到这一点。

这是URL本身:

baseURIs: [
{
service: "true",
location: "alex",
URL: "barcelonat",
},
{
service: "false",
location: "daniel",
URL: "RealMadrid",
},

这是json的输出(使用我的代码):

{u'URL': u'barcelona', u'location': u'alex', u'service': u'true'}
{u'URL': u'RealMadrid', u'location': u'daniel', u'service': u'false'}

如果字符串'RealMadrid'存在,我将尝试搜索该字典并打印“找到它”。这是代码:

#!/usr/bin/env python
import time
from datetime import datetime
import json
import urllib2
req = urllib2.Request('http://admin/alex/0.json')
response = urllib2.urlopen(req)
page = response.read()
user_dict = json.loads(page)
count = 0

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")
python python-3.x
3个回答
0
投票

您的代码段:

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k:
        print("Found it!")

在字典'RealMadrid'中搜索k,这意味着它将在字典keys中寻找该字符串。但是,在您作为输入提供的词典中,'RealMadrid'不是键,而是与'URL'键关联的值。您应将以上内容替换为:

for k in user_dict['baseURIs']:
    if k['URL'] == 'RealMadrid':
        print("Found it!")

0
投票

您正在搜寻dict键而不是值。试试:

for k in user_dict['baseURIs']:
    if 'RealMadrid' in k.values():
        print("Found it!")

0
投票

您可以访问值以将其与您的搜索字词进行比较

user_dict= {
    "baseURIs": [
    {
        "service": "true",
        "location": "alex",
        "URL": "barcelonat",
    },
    {
        "service": "false",
        "location": "daniel",
        "URL": "RealMadrid",
    }]
}


for key in user_dict['baseURIs']:
    if 'RealMadrid' in key.values():
        print("Found it!")
© www.soinside.com 2019 - 2024. All rights reserved.