简体   繁体   中英

Is there a way to access the nth JSON element with Python?

I have this JSON for example:

"products": {
    "5117293": {
        "id": 5117293,
        "brandId": 12,
        "price": "12$"
        "mediaById": {
            "104290597": {
                "id": "17_104290597",
                "group": "swatch",
                "type": "image",
                "src": "https://foo.com/image1.jpg"
              },
            "104725944": {
                "id": "7_104725947",
                "group": "main",
                "type": "image",
                "src": "https://foo.com/image2.jpg"
            }
        },
}

Let's say I want to access the second image image2.jpg . How do I do that with Python JSON library without knowing the ID? (accessing the second element in this example). Here's what I tried and obviously failed (EDIT: I realize it won't work, I just want a similar way).

image = json_content['products']["5117293"]["mediaById"][1]["src"]

This would print a key error.

To get the "second" index based on however the ordering falls, you can use:

nth = 2
nth_image_id = json_content['products']["5117293"]["mediaById"].keys()[nth - 1]
image = json_content['products']["5117293"]["mediaById"][nth_image_id]["src"]

As others have pointed out in the comments, the order may not be well defined. However in this case, if you know that the ID number will always be increasing, you might be able to use that to get the nth element, in another sense of "nth" that is well defined.

nth = 2
# determine the nth id
image_ids = json_content['products']["5117293"]["mediaById"].keys()
image_ids = [int(x) for x in image_ids]
image_ids.sort()
nth_image_id = image_ids[nth - 1]
# pull the nth image
image = json_content['products']["5117293"]["mediaById"][nth_image_id]["src"]

You can do it like this:

import json

j = """
{
    "products": {
        "5117293": {
            "id": 5117293,
            "brandId": 12,
            "price": "12$",
            "mediaById": {
                "104290597": {
                    "id": "17_104290597",
                    "group": "swatch",
                    "type": "image",
                    "src": "https://foo.com/image1.jpg"
                },
                "104725944": {
                    "id": "7_104725947",
                    "group": "main",
                    "type": "image",
                    "src": "https://foo.com/image2.jpg"
                }
            }
        }
    }
}
"""

d = json.loads(j)
print(list(d['products']['5117293']['mediaById'].items())[1][1]['src']) #for the second item
>>> https://foo.com/image2.jpg
#print(list(d['products']['5117293']['mediaById'].items())[0][1]['src']) #for the first item

I managed to do it by using a temporary list to get the media IDs and accessing the second element of that list.

images = json_content['products']["5117293"]['mediaById']
imagesList = []
for imageID in images:
    imagesList.append(imageID)
image = prod['mediaById'][imagesList[1]]['src']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM