Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

>>> 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading