Search code examples
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": "[email protected]",
  "authority": "CUSTOMER_USER",
  "firstName": "Davis",
  "lastName": "Smith",
  "name": "[email protected]"
},

  "email": "[email protected]",
  "authority": "CUSTOMER_USER",
  "firstName": "DONALDSON",
  "lastName": "ZAIK",
  "name": "[email protected]"
},

]

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 =

    '[email protected]'

ans =

    '[email protected]'

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'));
    
    • response(:).firstName lists all first names.
    • {response(:).firstName} build a cell array of first names.
      Example: {'Davis', 'DONALDSON'}
    • strcmp({...}, 'Davis') Returns a logical array with value 1 where firstName equals 'Davis' and 0 where not equal.
      Example: [0 1 0 0] is returned if only response(2).firstName = 'Davis'.
    • response(strcmp...) Uses logical indices for returning a new array where index equals 1.
      Example: response(logical([0 1 0 0])), returns an array (with length 1) containing the second struct of response.

    Sample code:

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

    Result:

    filtered_response = 
    
      struct with fields:
    
            email: '[email protected]'
        authority: 'CUSTOMER_USER'
        firstName: 'Davis'
         lastName: 'Smith'
             name: '[email protected]'
    

    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.