如何在包含字典和列表的python中迭代json对象

时间:2017-05-24 07:35:01

标签: json django python-2.7 dictionary

 {'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}]}
  

我想循环遍历这个使用web请求的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'。循环这种数据的正确方法是什么。

2 个答案:

答案 0 :(得分: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

for 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

答案 1 :(得分:0)

获取数据:

dt = dt[<all 'database related operations'>]