迭代python对象并对其进行过滤

时间:2019-07-02 18:21:21

标签: python json python-2.7 urllib2

我从Web服务获得的JSON表示法:

{
"students": [
    {
        "studentId": 127292,
        "studentName": "Mary"
    },
    {
        "studentId": 15555,
        "studentName": "Joe"
    }
  ]
}

我正在尝试迭代JSON对象并根据学生姓名获取学生ID。

例如,如果我必须获得studentId中的'Joe',该如何在Python中进行处理?

try:
    req = urllib2.Request(url, headers = header)
    response = urllib2.urlopen(req)
    jsonObject = json.load(response)

except Exception as e:
    print e

2 个答案:

答案 0 :(得分:1)

我建议将您的数据重新映射到字典中,您可以在其中按名称查找学生:

 public boolean Attempt_Find_Element(WebElement element) {
  int numAttemps = 0;
  int specifiedAttempts = 30;
  boolean success = false;

  do {
   numAttemps++;
   try {
    success = element.isDisplayed();
   } catch (NoSuchElementException | StaleElementReferenceException nse) {

   }
  } while (!success || numAttemps < specifiedAttempts);
  if (!success) {
   System.out.println("Couldn't load after " + numAttemps + " attempts");
  }
  return success;
 }

答案 1 :(得分:-1)

您可以遍历JSON对象以获取每个字段中的学生ID

studentIds = []
for obj in jsonObject:
    sID = obj['studentId']
    studentIds.append(sID)