Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Extract variables from json how to check if element exists

Not applicable

I am interacting with a third party service and I get the following responses :

if token valid 200 response

{
 ...
 "valid_until": "2018-09-21T00:00:00Z"
 }

if token is invalid I get 200 response with :

	{       "status": false, 

		"error": "Invalid Token Format!"

	}

I have the following extract policy

<ExtractVariables   name="Extract-valid-until-date">
    <DisplayName>Extract token chorus</DisplayName>
    <Source>chorusresponse</Source>
    <JSONPayload>
        <Variable name="valid_until">
            <JSONPath>$.valid_until</JSONPath>
        </Variable>
        <Variable name="response_error">
            <JSONPath>$.error</JSONPath>
        </Variable>
    </JSONPayload>
</ExtractVariables>

this is falling with following error if no valid_until date present in the json response:

{"fault":"{\"detail\":{\"errorcode\":\"steps.extractvariables.InvalidJSONPath\"},\"faultstring\":\"Invalid JSON path $.valid_until in policy Extract-valid-until-date.\"}"}

I tried $.?valid_until $.?(valid_until) but still not working,

is there any why to avoid error if the value is not present

Many thanks

Solved Solved
0 7 6,077
1 ACCEPTED SOLUTION

Not applicable

@miloud

Hi, you can use javascript policy.And in that you can use sth like

 var reqPayload = JSON.parse(context.getVariable('request.content'));
 var flag=reqPayload.hasOwnProperty('name');
 print(flag);

and use the flag accordingly. hasOwnProperty() will check if the property 'name' exists or not in payload. If not then will return false otherwise true.

View solution in original post

7 REPLIES 7