unable to parse json data to java script

ysharat
Participant II

Hi There,

Am trying to convert json incoming payload to javascript object using below

request: {"Email":"test","RequestIds":"1","IsFromCache":"true"}

Below is apige javascript

var s = context.getVariable('request.content');

var s1 = JSON.parse(s);

pirnt(s1)

when i print am getting the output as [object object].

0 7 1,519
7 REPLIES 7

sidd-harth
Participant V

Try this,

JSON.stringify(JSON.parse(s))

Did you try am getting excution error?

Yes, I have tried it.

What is the error you are getting?

Please find the attached for the error and the simple code snipped i had, essentially I want to evaluate the null values,if it was null want to return error 400 that json element value is mandatory.

Any update on it Siddharth?

@Popleys

I'm unable to find any "attached" error. I agree with Siddharth's solution. That should work.

var s = context.getVariable('request.content');
var s1 = JSON.parse(s); //This will convert the JSON string to an actual JS object
print(s1); //This will indeed print [Object object] as you are trying to print an object directly
print(JSON.stringify(s1))); //JSON.stringify will convert the s1 JS object back to a JSON string, which can then be printed

Also, for the usecase mentioned by you, you "could" manage with just the out-of-the-box policies.

<ExtractVariables name="ExtractMandatoryParams">
   <Source>request</Source>
   <JSONPayload>
      <Variable name="IsFromCache" type="boolean">
         <JSONPath>$.IsFromCache</JSONPath>
      </Variable>
   </JSONPayload>
</ExtractVariables>
  • Use a RaiseFault policy to return the 400 error message with a condition
<RaiseFault name="RaiseFault400">
 <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
 <FaultResponse>
   <Set>
     <StatusCode>400</StatusCode>
     <ReasonPhrase>Bad Request</ReasonPhrase>
   </Set>
 </FaultResponse>
</RaiseFault>
<Step>    
	<Condition>IsFromCache = null</Condition>    
	<Name>RaiseFault400</Name>
</Step>

Let us know how it goes.

when i print am getting the output as [object object].

The behavior you are reporting is expected.

The reason you see that is because when JavaScript converts a generic object to a string, the result is "[object object]". This isn't an Apigee thing, this is just how JavaScript works.

If you would like to see the JSON representation of the object, then you need to call JSON.stringify() on it, before printing.

var s = context.getVariable('request.content');
var s1 = JSON.parse(s);
print(s1);                  // [object object]
print(JSON.stringify(s1));  //  {"Email":"test",...}