arraysjsonmatlabmatlab-struct

How to access certain elements in Matlab structure array


I am working on a Matlab project that connects with Thingsboard website. I use webread function to get the response from the server which sends information as JSON. When I send a request to get the users' information, I should get the information in the following format:

  [
{
  "email": "Davis@gmail.com",
  "authority": "CUSTOMER_USER",
  "firstName": "Davis",
  "lastName": "Smith",
  "name": "JOHN@gmail.com"
},

  "email": "DONALDSON@hotmail.com",
  "authority": "CUSTOMER_USER",
  "firstName": "DONALDSON",
  "lastName": "ZAIK",
  "name": "meraj@hotmail.com"
},

]

However, the response that I get in Matlab using webread function is as follows:

4×1 struct array with fields:
email
authority
firstName
lastName
name

and when I access any field like email, it shows the emails of all the users as follows:

response = webread("serverurl");

response.email 


ans =

    'Davis@gmail.com'

ans =

    'DONALDSON@hotmail.com'

What I want to know is how to get a specific user's information by knowing one field only. For example, I want to get the email,lastname and authority of the user Davis by knowing the first name "Davis".

I really appreciate your help in this matter.


Solution

  • You can use the following syntax:

    filtered_response = response(strcmp({response(:).firstName}, 'Davis'));
    

    Sample code:

    %Build an array containing two structures (just for the example)
    %Assume response is the result of webread 
    response = [struct('email', 'Davis@gmail.com', 'authority', 'CUSTOMER_USER', 'firstName', 'Davis', 'lastName', 'Smith', 'name', 'JOHN@gmail.com');...
                struct('email', 'DONALDSON@hotmail.com', 'authority', 'CUSTOMER_USER', 'firstName', 'DONALDSON', 'lastName', 'ZAIK', 'name', 'meraj@hotmail.com')];
    
    filtered_response = response(strcmp({response(:).firstName}, 'Davis'));
    

    Result:

    filtered_response = 
    
      struct with fields:
    
            email: 'Davis@gmail.com'
        authority: 'CUSTOMER_USER'
        firstName: 'Davis'
         lastName: 'Smith'
             name: 'JOHN@gmail.com'
    

    Now you can get any field like filtered_response.email in case there is only one struct with firstName = 'Davis'.
    And filtered_response(:).email in case there is more than one matching struct.