从JSON列表数组中提取一个元素

huangapple go评论61阅读模式
英文:

Extract an element from json list array

问题

你想要的格式是这样的:

"subscriptions": [             
  {                
    "totalAmount": { "amount": "450.0" },
    "tax": { "amount": "0.0" }                
  },
  {               
    "totalAmount": { "amount": "25.0" },
    "tax": { "amount": "0.0" }                                
  }
]  

你可以使用以下代码来实现这个目标:

new_dict = {}
for subscription in data[0]['client']['Outcome']['Options'][0]['subscriptions']:
    new_subscription = {
        'totalAmount': {'amount': subscription['totalAmount']['amount']},
        'tax': {'amount': subscription['tax']['amount']}
    }
    new_dict.setdefault('subscriptions', []).append(new_subscription)

这段代码会循环遍历每个订阅,然后将它们的'totalAmount'和'tax'值提取到新的字典中,最后将这些字典组成一个新的'subscriptions'列表。

英文:
[
  {     
    "confirmed": false,
    "client": {       
      "Outcome": {
        "ResponseId": "64352036ead00dc1fd8d",
        "Options": [
          {
            "optionState": "AUTHORISED",
           
            "Endorsements": [
              {
                "PointId": "7e8fb6e0-0435-45c3-b2a5-82cb2074bf63", 
                "LifetimeIds": ["00002"], 
                "Code": "001",
                "Name": "Name of the provider",
                "Wording": "Wording goes here",
                "Variables": [{ "name": "${value}", "value": "450" }]
              }
            ],
            "subscriptions": [             
              {                
                "totalAmount": { "amount": "450.0", "currencyCode": "EUR" },
                "tax": { "amount": "0.0", "currencyCode": "EUR" },
                "subscription": { "amount": "450.0", "currencyCode": "EUR" },
                "code": "Movie",
                "message": "You have access to all movies in the library"
              },
              {               
                "totalAmount": { "amount": "25.0", "currencyCode": "EUR" },
                "tax": { "amount": "0.0", "currencyCode": "EUR" },
                "subscription": { "amount": "25.0", "currencyCode": "EUR" },
                "code": "Library",
                "message": "You are able to borrow books"
              }
            ]           
          }
        ]
       }       
      },
     
    "startDate": "17-04-2023",   
    "name": "Joe Blogg",
    "email": "joe@blogg.com",
    "phoneNumber": "01234567890" 
  }
]

I wounder if someone can help me, I'm trying to loop through 'subscriptions' element and print out only the ['tax']['amout'] and ['totalAmount']['amount'] - adding them into a dictionary. But I'm getting an error message that '

list indices must be integers or slices, not str

so I'm looking to have a new dictionary that has this format:

"subscriptions": [             
              {                
                "totalAmount": { "amount": "450.0" },
                "tax": { "amount": "0.0"}
                
              },
              {               
                "totalAmount": { "amount": "25.0"},
                "tax": { "amount": "0.0"}
                                
              }
            ]          
new_dict = {}
for i in data['client']['Outcome']['Options']['subscriptions']:
    new_dict.update({'totalAmount': i['totalAmount']['amount']})
    new_dict.update({'tax': i['tax']['amount']})
    

The code about is what I was trying to use to parse it, but It's giving me error - so I can't build a new dictionary with the values that I'm interested in.

Any help would be appreciated.

答案1

得分: 1

Here is the translated code:

如果您每个列表只有一条记录您可以使用

new_dict = {'subscriptions': []}

#                 这里 --v                           这里 --v
for subscription in data[0]['client']['Outcome']['Options'][0]['subscriptions']:
    new_dict['subscriptions'].append({'totalAmount': {'amount': subscription['totalAmount']['amount']},
                                      'tax': {'amount': subscription['tax']['amount']}})

输出:

>>> json.dumps(new_dict, indent=4)
{
    "subscriptions": [
        {
            "totalAmount": {
                "amount": "450.0"
            },
            "tax": {
                "amount": "0.0"
            }
        },
        {
            "totalAmount": {
                "amount": "25.0"
            },
            "tax": {
                "amount": "0.0"
            }
        }
    ]
}

(Note: I've replaced the HTML entities like " with their corresponding characters in the translated code.)

英文:

If you have only one record per list, you can use:

new_dict = {'subscriptions': []}

#                 HERE --v                           HERE --v
for subscription in data[0]['client']['Outcome']['Options'][0]['subscriptions']:
    new_dict['subscriptions'].append({'totalAmount': {'amount': subscription['totalAmount']['amount']},
                                      'tax': {'amount': subscription['tax']['amount']}})

Output:

>>> json.dumps(new_dict, indent=4)
{
    "subscriptions": [
        {
            "totalAmount": {
                "amount": "450.0"
            },
            "tax": {
                "amount": "0.0"
            }
        },
        {
            "totalAmount": {
                "amount": "25.0"
            },
            "tax": {
                "amount": "0.0"
            }
        }
    ]
}

huangapple
  • 本文由 发表于 2023年4月17日 19:28:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034672.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定