Reputation: 45
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:
"
to be in outputI tried:
for key, value in json_f.items():
print(key, value)
But it's not what I want.
Upvotes: 0
Views: 42
Reputation: 515
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)
Upvotes: -1
Reputation: 71517
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
Upvotes: 3