Python,通过/ sort解析JSON顺序

时间:2018-04-26 10:22:50

标签: python json

我有这个JSON数据:

 "InstanceProfileList": [
                {
                    "InstanceProfileId": "AIPAI6ZC646GGONRADRSK", 
                    "Roles": [
                        {
                            "AssumeRolePolicyDocument": {
                                "Version": "2012-10-17", 
                                "Statement": [
                                    {
                                        "Action": "sts:AssumeRole", 
                                        "Effect": "Allow", 
                                        "Principal": {
                                            "Service": [
                                                "ec2.amazonaws.com", 
                                                "ssm.amazonaws.com"
                                            ]
                                        }
                                    }
                                ]
                            }, 
                            "RoleId": "AROAJMI3DEQ4AW5JJMFII", 
                            "CreateDate": "2018-03-23T15:23:28Z", 
                            "RoleName": "ec2ssmMaintWindow", 
                            "Path": "/", 
                            "Arn": "arn:aws:iam::279052847476:role/ec2ssmMaintWindow"
                        }
                    ]

我使用以下代码来解析它:

def get_user_group_service(element):
    s = ''
    for e in element['AssumeRolePolicyDocument']['Statement']:
        p = e['Principal']
        if 'Federated' in p:
            s += p['Federated']
        if 'Service' in p:
            obj = p['Service']
            if type(obj) is str:
                s += obj  # element is string
            else:
                s += ''.join(obj)  # element is array of strings
        if 'AWS' in p:
            s += p['AWS']
    return s

现在,问题是有时Service元素包含:

ec2.amazonaws.com ssm.amazonaws.com

有时候:

ssm.amazonaws.com ec2.amazonaws.com

订单每次都不同。

它的显示顺序无关紧要,我只需要输出一致。有没有办法按字母顺序排序这个输出?

我用谷歌搜索它似乎obj.sort()将修复它但不知道如何应用它。

3 个答案:

答案 0 :(得分:1)

根据我的理解,你想要一个空格分隔的有序字符串。这是我的方法。

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header text-center d-block">
        <h5 class="modal-title d-inline-block" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<强>输出:

x = 'ec2ssmMaintWindow,AmazonSSMMaintenanceWindowRole,ec2.amazonaws.com ssm.amazonaws.com'
sorted_only_space_sparated = [ ' '.join( z for z in sorted(y.split(' '), reverse=True)) for y in x.split(',')]

print(','.join(str(i) for i in sorted_only_space_sparated))

如果有帮助,请告诉我。

答案 1 :(得分:0)

问题是你的字符串有大写和小写都使用sorted方法中的key参数来排序数据而不考虑案例:

Services=["ec2ssmMaintWindow","AmazonSSMMaintenanceWindowRole","ssm.amazonaws.com" ,"ec2.amazonaws.com"]
s=""
s+=" ".join(sorted(Services,key=lambda x:x.lower()))

OUT

AmazonSSMMaintenanceWindowRole ec2.amazonaws.com ec2ssmMaintWindow ssm.amazonaws.com

如果服务总是有这4个值,那么对列表进行排序将重新排列索引并使索引每次都相同,然后您可以通过索引简单地访问该值。

答案 2 :(得分:0)

谢谢大家,我找到了另一个解决方案:我遇到了问题,因为有问题的代码是本机python3代码(我在python 2.7下运行它)而obj.sort()抛出错误

unicode' object has no attribute 'sort', 

我更正了代码,以便检查obj是否为unicode

def get_user_group_service(element):
    s = ''
    for e in element['AssumeRolePolicyDocument']['Statement']:
        p = e['Principal']
        if 'Federated' in p:
            s += p['Federated']
        if 'Service' in p:
            obj = p['Service']
            if  type(obj) in (str, unicode):
                s += obj  # element is string
            else:
                obj.sort()
                s += ''.join(obj) # element is array of strings


        if 'AWS' in p:
            s += p['AWS']
    return s

现在,每个itteration按字母顺序对值进行排序