JimmyOppa
JimmyOppa

Reputation: 67

How to parse values from a specific key of multiple JSON objects python

I am trying to parse the key "tags" from the below JSON.

data = [{
    "12233":{
    "title": "The Title",
    "id": "12233",
    "tags": ["tag1", "tag2", "tag3"],
    },
    "122223":{
    "title": "The Title",
    "id": "122223",
    "tags": ["tag4", "tag5", "tag6"],
    },
    "122344":{
    "title": "The Title",
    "id": "122344",
    "tags": ["tag7", "tag8", "tag9"],
    }
}]

I have tried this so far,

data = data[0]
tags_list = []

for tags in data:
    tags_list.append(tags["122344"])

print(tags_list)

But it only extracts the first object, I want the result to be like this,

tags_list = ["tag1", "tag2", "tag3", "tag4", "tag5", "tag6","tag7", "tag8", "tag9"]

Upvotes: 0

Views: 190

Answers (3)

sarath ravi
sarath ravi

Reputation: 481

is this will solve your problem?

tags_list = [item for k in data for t in k for item in k[t]['tags']]

Upvotes: 3

eroot163pi
eroot163pi

Reputation: 1815

Use itemgetter on all values of dictionary data[0] and sum all items to empty list []

from operator import itemgetter

data = [{
    "12233":{
    "title": "The Title",
    "id": "12233",
    "tags": ["tag1", "tag2", "tag3"],
    },
    "122223":{
    "title": "The Title",
    "id": "122223",
    "tags": ["tag4", "tag5", "tag6"],
    },
    "122344":{
    "title": "The Title",
    "id": "122344",
    "tags": ["tag7", "tag8", "tag9"],
    }
}]

tag_getter = itemgetter('tags')
# map to get list of all tags
# Adding all the list of tags to []
sum(map(tag_getter, data[0].values()), [])
['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']

If you want to merge all tags from all the entries of list then use

from operator import itemgetter
tag_getter = itemgetter('tags')
def all_tags(d):
    return sum(map(tag_getter, d.values()), [])
sum(map(all_tags, data), [])

Upvotes: 1

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

In stead of a single loop, you need two loops to iterate over the inner dictionaries. Try this :

tags_list = []
for k in data:
    for t in k:
        tags_list.extend(k[t]['tags'])

Output tags_list :

['tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'tag6', 'tag7', 'tag8', 'tag9']

Upvotes: 0

Related Questions