Home > OS >  Print all of element inside Bracket json in python
Print all of element inside Bracket json in python

Time:04-20

I want to get all 'name' from this json and separate by comma

{
    "example": [
        {
            "id": 1,
            "name": "blah"
        },
        {
            "id": 2,
            "name": "nah"
        },
        {
            "id": 5,
            "name": "krah",
        },
        {
            "id": 10,
            "name": "ugh"
        }
    ],
}

when im trying to:


example = r_json['example']['name']
print(example)

it returns me:

    example = r_json['example']['name']
TypeError: list indices must be integers or slices, not str

output i want is something like:

blah, nah, krah, ugh

CodePudding user response:

Just as the error says, the value under r_json['example'] is a list of dictionaries, so you can't access it like: r_json['example']['name']. One way to get the names is to use a list comprehension:

example = [d['name'] for d in r_json['example']]
print(*example)

Output:

blah nah krah ugh

CodePudding user response:

The value in "example" is a list. To access items you need to use an index. e.g.

>>> r_json["example"][0]["name"]
'blah'

If you want to get all of the names, you need to loop through each item in the list.

>>> for i in range(len(r_json["example"])):
...    print(r_json["example"][i]["name"])
blah
nah
krah
ugh

A simpler way to do this would be to directly iterate over the list and not use an index:

>>> for example in r_json["example"]:
...    print(example["name"])
blah
nah
krah
ugh

To put them in a list you can do:

>>> names = []
>>> for example in r_json["example"]:
...    names.append(example["name"])
>>> names
['blah', 'nah', 'krah', 'ugh']

An even easier way is to use a comprehension:

>>> names = [example["name"] for example in r_json["example"]]
>>> names
['blah', 'nah', 'krah', 'ugh']

Once you have the names you can use str.join to make your final result:

>>> ", ".join(names)
'blah, nah, krah, ugh'

As a one liner just for fun:

>>> ", ".join(example["name"] for example in r_json["example"])

An even more fun one-liner!

>>> from operator import itemgetter
>>> ", ".join(map(itemgetter("name"), r_json["example"]))
'blah, nah, krah, ugh'
  • Related