简体   繁体   中英

Get Only Nested Key-Value Pairs From Dictionary?

Given the following dictionary in python, I'm interested in getting only inner key-value pairs.

{
  "destination": {
    "name": "accountName"
  },
  "orderData": {
    "sourceOrderId": "1234512345",
    "items": [
      {
        "sku": "Business Cards",
        "sourceItemId": "1234512346",
        "components": [
          {
            "code": "Content",            
            "fetch": true,
            "path": "http://www.w2psite.com/businessCard.pdf"
          }
        ]
      }
    ],
    "shipments": [
      {
        "shipTo": {
          "name": "John Doe",
          "companyName": "Acme"
        },
        "carrier":{
          "code": "fedex",
          "service": "ground"
        }
      }
    ]
  }
}

In other words I want:

name: accountName
sourceOrderId: 1234512345
sku: Business Cards
sourceItemId: 1234512346

etc... and I don't want:

destination, orderData etc...

How can I do this?

Few things to Note:

  1. I don't want " to be in output
  2. There could be multiple inner values and what I showed is just an example.

I tried:

for key, value in json_f.items():
    print(key, value)

But it's not what I want.

The easiest way to traverse an arbitrarily nested structure is usually a recursive function, eg:

>>> def print_inner_json(obj):
...     for k, v in obj.items():
...         if isinstance(v, list):
...             for i in v:
...                 if isinstance(i, dict):
...                     print_inner_json(i)
...         elif isinstance(v, dict):
...             print_inner_json(v)
...         else:
...             print(f"{k}: {v}")
...
>>> import json
>>> print_inner_json(json.loads(json_f))
name: accountName
sourceOrderId: 1234512345
sku: Business Cards
sourceItemId: 1234512346
code: Content
fetch: True
path: http://www.w2psite.com/businessCard.pdf
name: John Doe
companyName: Acme
code: fedex
service: ground

json_obj = {
  "destination": {
    "name": "accountName"
  },
  "orderData": {
    "sourceOrderId": "1234512345",
    "items": [
      {
        "sku": "Business Cards",
        "sourceItemId": "1234512346",
        "components": [
          {
            "code": "Content",            
            "fetch": True,
            "path": "http://www.w2psite.com/businessCard.pdf"
          }
        ]
      }
    ],
    "shipments": [
      {
        "shipTo": {
          "name": "John Doe",
          "companyName": "Acme"
        },
        "carrier":{
          "code": "fedex",
          "service": "ground"
        }
      }
    ]
  }
}

name = json_obj["destination"]["name"]
source_order_id = json_obj["orderData"]["sourceOrderId"]
sku = json_obj["orderData"]["items"][0]["sku"]
source_item_id = json_obj["orderData"]["items"][0]["sourceItemId"]
print(name)
print(source_order_id)
print(sku)
print(source_item_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM