【问题标题】:How to iterate over json object in python containing dictionary and list如何在包含字典和列表的python中迭代json对象
【发布时间】:2017-10-24 09:56:05
【问题描述】:
 {'PCCandidateDetails': {'BatchId': '456279',
  'Candidate': 'Noori sahi ',
  'CandidateId': '9124657',
  'CenterName': 'K',
  'ProjectName': 'PKKVY',
  'QPName': 'Domestic Data Entry Operator(SSC/Q2212)',
  'TrainingProviderName': 'OrionEdutechPrivateLimited'},
 'PCTestScores': [{'MaxScore': 12,
   'PCId': 'SRC/N3022_PC1',
   'PCName': 'obtain sufficient information from the customer /client to understand the need and perform initial task',
   'Percentage': 0,
   'YourScore': 0},
  {'MaxScore': 15,
   'PCId': 'SRC/N3022_PC10',
   'PCName': 'compares transcribed data, as displayed on a visual screen, document and corrects any errors with the source',
   'Percentage': 0,
   'YourScore': 0},
  {'MaxScore': 5,
   'PCId': 'SSC/N3022_PC11',
   'PCName': 'obtain help or advice from specialist if the problem is outside his/her area of competence or experience',
   'Percentage': 0,
   'YourScore': 0}]}

我想遍历我使用网络请求获得的这个 json 对象。

import requests,ast
r = requests.get("some url")
data = r.text
data_dic = ast.literal_eval(data)

当我尝试循环 Json 时,我无法获取键值对中的预期输出。我想要这样的输出

BatchId : 456279 
Candidate : Noori sahi
CandidateId :9124657 ...

等等。下面的代码是我的方法,但列表中的字典导致循环出现问题。

for i in data_dic:
        for k,v in i.iteritems():
            print k,v

我得到的错误是“str”对象没有属性“iteritems”。循环此类数据的正确方法是什么。

【问题讨论】:

    标签: json django python-2.7 dictionary


    【解决方案1】:

    这适用于您的示例(python 3.5.2),但我不知道是否是最好的方法(我的意思是,也许有一些 json 解析函数更易于使用):

    for v, k in itms.items():
        if not isinstance(k, list):
            for x, y in k.items():
                print(x,':', y)
        else:
            for i in k:
                for s, m in i.items():
                    print(s,':', m)
    

    结果:

    CandidateId : 9124657
    BatchId : 456279
    QPName : Domestic Data Entry Operator(SSC/Q2212)
    CenterName : K
    ProjectName : PKKVY
    Candidate : Noori sahi 
    TrainingProviderName : OrionEdutechPrivateLimited
    Percentage : 0
    PCName : obtain sufficient information from the customer /client to understand the need and perform initial task
    MaxScore : 12
    YourScore : 0
    PCId : SRC/N3022_PC1
    Percentage : 0
    PCName : compares transcribed data, as displayed on a visual screen, document and corrects any errors with the source
    MaxScore : 15
    YourScore : 0
    PCId : SRC/N3022_PC10
    Percentage : 0
    PCName : obtain help or advice from specialist if the problem is outside his/her area of competence or experience
    MaxScore : 5
    YourScore : 0
    PCId : SSC/N3022_PC11
    

    适用于 python 2.7。只删除print中的括号

    for v, k in itms.items():
        if not isinstance(k, list):
            for x, y in k.items():
                print x,':', y
        else:
            for i in k:
                for s, m in i.items():
                    print s,':', m
    

    【讨论】:

      【解决方案2】:

      获取数据使用:

      import json
      data = json.loads(request.body)
      print data['PCTestScores']
      for values in data['PCTestScores']:
          print values
          print values['PCId']
          print values['PCName']
          print values['Percentage']
          print values['MaxScore']
          print values['YourScore']
      

      【讨论】:

      • 我已经试过了,但是输出是一样的。我只有循环时遇到问题,因为它有一个字典,另一个是列表中的字典。
      • 你能发布你的代码吗?因为 dict_data 不在您的 JSON 响应中。或者你在说PCTestScores
      • 导入请求,json 在[15]中:r = requests.get('some url') 在[16]中:data = json.loads(r.content) 在[17]中:type(数据)输出[17]:字典
      猜你喜欢
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 2018-10-17
      • 1970-01-01
      • 2014-11-20
      • 2014-09-26
      相关资源
      最近更新 更多