Python: How to get index from an Array of JSON?

Question:

So, I was able to answer my question before on how to get the value of a JSON from an array of JSON. But now I’m trying to convert it in Python(for selenium).

Here is the Array of JSON:

[
    {
        "id": 3328367679,
        "inbox_id": 35584,
        "subject": "Open this message"
    },
    {
        "id": 3328364404,
        "inbox_id": 35584,
        "subject": "Another message"
    },
    {
        "id": 3328363502,
        "inbox_id": 35584,
        "subject": "Open this message"
    },
    {
        "id": 3328357254,
        "inbox_id": 35584,
        "subject": "Open this message"
    },
    {
      "id": 3328349654,
      "inbox_id": 35584,
      "subject": "Open this message"
    }
  ]

Below is my script, it’s working in Cypress Javascript. This works by getting the index of JSON that gives the first same "subject" which is "Open this message" and then uses the same index to return the "id" which is 3328367679

function getMessageID() {
        cy.request({
            url: Cypress.env('url'),
            method: 'GET',
            headers: {
                'Api-Token': Cypress.env('token'),
                'Content-Type': 'application/json;charset=utf-8'
            },
        })
        .then((response) => {
            expect(response.status).to.eq(200)
            var messages = response.body
            var messageTitle = 'Open this message'
            for (var i = 0; i < messages.length; i++){
                if (messages[i].subject == messageTitle){
                    return messages[i].id
                    break;
                    }
            }
        })
    }
    getMessageID()

How do I convert this in Python? This is my current script and it’s giving me value of None when I print it. I run the get_id in the feature file since they’re connected:

def get_messages():
    url = "https://uri.io/api/accounts/fdsdfs/inboxes/dfsfds/messages/"
    headers = {
        "Content-Type": "application/json;charset=utf-8",
        "Api-Token": "123345dsfgsdrgf3456dfg5634dfv5"
    }
    response = requests.get(url=url, headers=headers)
    return response.json()

@staticmethod
def get_id():
    messages = ClassName.get_messages()
    message_title = "Open this message"
    for item in messages:
        if item["subject"] == message_title:
            print("Message id is " + item["id"])
            return item["id"]
        break

Tried as well using for loop within a for loop:

def get_id():
    messages = ClassName.get_messages()
    message_title = "Open this message"
    for json_item in messages:
        for message_item in json_item:
            if message_item["subject"] == message_title:
                print("Message id is " + str(message_item["id"]))
            return message_item["id"]
        break

I was able to print a subject using this code. How do I use indexes in Python? print(messages[0]["subject"])

    @staticmethod
def get_id():
    messages = ClassName.get_messages()
    message_title = "Open this message"
    # print(messages)
    print(messages[0]["subject"])
    # for item in messages:
    #     if messages[item]["subject"] == message_title:
    #         print("Message id is " + messages[item]["id"])
    #         return messages[item]["id"]
    #     break
Asked By: Faith Berroya

||

Answers:

The problem that will occur from what you have is the concatenation part. You can not concatenate a string to an int so inside your loop you should cast the id to string:

message_title = "Open this message"
for item in messages:
    if item["subject"] == message_title:
        print("Message id is " + str(item["id"]))
        return item["id"]
    break

Apart from that if the response is the same as the one you posted on the top of your example the return response.json() is not required, you can use it already as is so simply return response

You code for parsing in the end is working fine after those adjustments.

If that does not solve your issue print the messages variable inside the get_id function and update your question because the error is in the api-call or the formatted response and not in the parsing of it.

Answered By: pr1nc3

Thank you so much @pr1nc3 for helping me out! There was a problem with assigning the JSON value in the variable because of the None being returned. Not sure why we have None but I reconstructed the code and combined it into just 1 (thanks for this strategy @pr1nc3 🙂 ).

This is the working code

def get_id():
    url = "https://uri.io/api/accounts/fdsdfs/inboxes/dfsfds/messages/"
    headers = {
        "Content-Type": "application/json;charset=utf-8",
        "Api-Token": "123345dsfgsdrgf3456dfg5634dfv5"
    }
    messages = requests.get(url=url, headers=headers).json()
    message_title = "Open this message"
    total_messages = len(messages)
    for i in range(total_messages):
        if messages[i]["subject"] == message_title:
            return messages[i]["id"]
            break
Answered By: Faith Berroya