Reputation: 409
I want to iterate through a JSON file using Python and print the a set of keys.
For example:
import json
KEYS_TO_PRINT = ["id", "channel.title"]
my_data = {"items": [{"id": 1, "channel": {"channelid": "channelid1", "title": "nailed_it1"}}, {"id": 2, "channel": {"channelid": "channelid2", "title": "nailed_it2"}}]}
this_row = []
for item in my_data["items"]:
for key in KEYS_TO_PRINT:
try:
if "." in key:
split_up = key.split(".")
print item[split_up[0]][split_up[1]]
else:
print item[key]
except KeyError:
print "Oops"
However, it's pretty ugly. Is there a neater way?
Upvotes: 1
Views: 148
Reputation: 524
Consider something like this, you can specify a subkey using "." to delimit your keys. Here's an example:
KEYS_TO_EXPORT = ["id", "dateTime", "title", "channel.title"]
item = {"id": 1, "channel": {"title": "nailed_it"}}
this_row = []
for export_key in KEYS_TO_EXPORT:
try:
value = item
for key in export_key.split("."):
value = value[key]
this_row.append(str(value).encode('utf-8'))
except KeyError:
this_row.append("")
Edit to work with list:
This solution can easily be extended to work with a list of items as per the edit to the original question as follows. Also I switched to using .get
like Will suggested in the comments.
KEYS_TO_PRINT = ["id", "channel.title"]
my_data = {"items": [
{"id": 1, "channel": {"channelid": "channelid1", "title": "nailed_it1"}},
{"id": 2, "channel": {"channelid": "channelid2", "title": "nailed_it2"}},
{"id": 3}
]}
this_row = []
for item in my_data["items"]:
for export_key in KEYS_TO_PRINT:
value = item
for key in export_key.split("."):
value = value.get(key)
if value == None: break
this_row.append(str(value).encode('utf-8') if value != None else "")
print this_row
Upvotes: 2