Regex to find attributes which has null values

5.2k Views Asked by At

I'm using REST Assured framework for the API testing and am facing some difficulties in finding attributes having null values. I really dont have any idea about regex :P

So, the API response is like

"data": [
        {
            "type": "social",
            "id": "164",
            "attributes": {
                "created_time": "2014-09-12",
                "currency": "INR",
                "budget": 381000,
                "end_time": null,
                "name": "Untitled",
                "start_time": "2022-09-12",
                "updated_time": "2014-09-12"
            }

I need to find attributes which is having null values like "end_time". If there is any other way to find such attributes, It will be really helful.

Thanks in advance!!

1

There are 1 best solutions below

4
On BEST ANSWER

To search for null attributes in JSON text, you can use following regex:

/"([^"]+)": null/

Above regular expression will capture in group 1 all the attributes with value null.

Explanation:

  • " - match quote
  • ( - begin of capture group
  • [^"]+ - will match (capture) one or more characters which are not quote
  • ) - end of capture group
  • " - match quote
  • : null - literally match colon, followed by space, followed by null

Above explanation translated to plain English: Capture all characters which are between quotes, followed by colon, space and null.

Depending on the language you use to execute the regular expression, you need to specify the global flag to match all the attributes. The first matching group usually is the first element of the result and is array.

Depending on your language, the forward slashes '/' might be required or not - regex could be specified as string or the language could support regex notation - with slashes. In the latest,usually the global flag is specified by adding g after the closing slash.

In Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// Retrieve response from the REST API    
String json_response = receiveResponse();

// Define the regex pattern
String pattern = "\"([^\"]+)" *: *null";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(json_response);
if (m.find( )) {
   // Print the entire match
   System.out.println("Found value: " + m.group(0) );   // > "end_time": null
   // Print capture group 1
   System.out.println("Found null for: " + m.group(1) ); // > end_time
} else {
  System.out.println("NO MATCH");
}

You can iterate over all matching fields:

while (m.find( )) {
   System.out.println("Found value: " + m.group(0) );
   System.out.println("Found null for: " + m.group(1) );
}