Search code examples
javascriptjsongraphqlgraphql-jsk6

Trying to log JSON response in terminal using javascript


When I type the following command

console.log("Response = " +JSON.stringify(response.body));

I get the following response

Response = {"data":{"getPortalByOrganizationAliasAndSlug":{"portalId":"123f3redvq","expireAt":null,"accountId":"1","templateId":"stephendemo","arePortalDefaultsOverriden":null,"template":{"allContent":null,"digitalAssets":[],"recommendedContent":null,"allTopics":null,"recommendedTopics":null,"templateId":"stephendemo","organizationId":"fqewf2134214","header":"","footer":"","favicon":"null","logoPath":"/img/pages/logo.png","logo":"https://dev-v3-23-dev-assets.s3.amazonaws.com/r232r/232332/3232/stephendemo/image-logo-1603086511.png","primaryColor":"undefined","secondaryColor":"#b5b3b3","labels":{"key":"key","value":"value","__typename":"Tuple"},"orgLegalName":"Stephen Carvalho","supportTextLine":"Support","supportEmailAddress":null,"termsOfService":"http://2323.com","copyright":"Stephen Carvalho","invitationDelivery":"MANUALLY","magicLink":false,"emailAndPAssword":false,"scope":"2332","searchPlaceholder":"search","inputPlaceholder":null,"orgDisplayName":"Stephen","styles":{"contentCards":{"type":"STANDARD","__typename":"ContentCardStyle"},"__typename":"TemplateStyles"},"__typename":"TemplatePortalContent"},"templateBuyerPortal":null,"driftEnabled":false,"driftConfig":null,"portalState":"enabled","portalSlug":"stephendemo","userOwnerId":"1","userOwner":{"organizationId":"oSvjLe1paYKg","firstName":"Stephen","lastName":"Carvalho","email":"[email protected]","accountId":"1","portalIds":null,"phone":null,"title":null,"__typename":"User"},"teamMembers":null,"organizationAlias":"stephensdemo","companyId":1,"organizationId":"oSvjLe1paYKg","scope":"CONTENT_PORTAL","isContentPortalv3":true,"landingPageUrl":null,"isLandingPageUrlEnabled":false,"blockedDomains":[],"exclusiveContent":{"digitalAssets":[{"id":"2","status":5,"__typename":"ExclusiveDigitalAsset"}],"__typename":"ExclusiveContentType"},"__typename":"Portal"}}}  source=console

I want to save the portal id in a variable.

I tried this command to first print only the part from the data variable

let responsedata = JSON.parse(response.body.data);
 console.log(responsedata);

But I get the following error

ERRO[0002] SyntaxError: invalid character 'u' looking for beginning of value
running at parse (native)

Even if I try the following command I get the same error

let responsedata = JSON.parse(response.body.data.getPortalByOrganizationAliasAndSlug.portalId);
console.log(responsedata);

Could anyone help me understand how do I print the variables inside the response such as the values of portalID or accounted?


Solution

  • You are trying to parse the value inside your json and not the json response body. Try the below code.

    let responsedata = JSON.parse(response.body).data;
    console.log(responsedata);