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:
- I don’t want
"to be in output - 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