How to change response data extract in POSTMAN - json

as in this example, I get the data from Starwar's GraphQL: https://swapi-graphql.netlify.app/.netlify/functions/index
Body Request:
query {
allFilms {
films {
title
}
}
}
Response data:
{
"data": {
"allFilms": {
"films": [
{
"title": "A New Hope"
},
{
"title": "The Empire Strikes Back"
},
{
"title": "Return of the Jedi"
},
{
"title": "The Phantom Menace"
},
{
"title": "Attack of the Clones"
},
{
"title": "Revenge of the Sith"
}
]
}
}
}
However, I want to get the responding data as an array of "films" like this:
[
{
"title": "A New Hope"
},
{
"title": "The Empire Strikes Back"
},
{
"title": "Return of the Jedi"
},
{
"title": "The Phantom Menace"
},
{
"title": "Attack of the Clones"
},
{
"title": "Revenge of the Sith"
}
]
So how can I do that? (if I'm not wrong, it's related to Pre-request Script)

You won't be able to change the format of the response, but you can process the result so it provides exactly what you want. I created this request on Postman so you can see how I've done it.
You need to transform the response when you fetch it, in postman you would do so in the Tests tab (i.e. post-response script vs pre-request):
// Getting the response data into a variable response
const response = pm.response.json();
// Converting the original response to the format you want
const filmArray = response.data.allFilms.films
// Logging it to the console so you can verify the results
console.log(filmArray)
This is the result of that console.log on postman:

Related

How to iterate through data from a JSON file in VueJS/Gridsome using GraphQL?

I am getting my feet wet in VueJS/Gridsome and I am trying to make a simple site to start off. What I am looking to do is store all my data locally in a JSON file and pull it into my page/component using GraphQL. I am able to see the data load however I cannot iterate through every object; instead it shows me all the data.
I have tried changing the way I layout my JSON objects schemas, tried separating into multiple json files (Do not want to do this) and have played with different v-for parameters. On the Gridsome Docs and Youtube Tutorials everyone is pulling from markdown and generating pages from each markdown file or using some sort of API. I want to accomplish this in a single JSON file.
videos.json
[
{
"title": "vid 1",
"url": "url1"
},
{
"title": "vid 2",
"url": "url2"
}
]
GraphQL Query
{
allVideo {
edges {
node{
id
data {
title
url
}
}
}
}
}
GraphQL Results
{
"data": {
"allVideo": {
"edges": [
{
"node": {
"id": "6b3cddf43cce8f8a0fb122d194db6edc",
"data": [
{
"title": "vid 1",
"url": "https://youtube.com"
},
{
"title": "vid 2",
"url": "https://youtube.com"
}
]
}
}
]
}
}
}
Videos.vue
<template>
<Layout>
<h1>Videos</h1>
<div v-for="edge in $page.allVideo.edges" :key="edge.node.id">
{{edge.node.data}}
</div>
</Layout>
</template>
<page-query>
query Videos {
allVideo {
edges {
node {
id
data {
title
url
}
}
}
}
}
</page-query>
Page Result:
Videos
[ { "title": "vid 1", "url": "url1" }, { "title": "vid 2", "url": "url2" } ]
I expect there to be an ID for each video entry, however it seems that the data collection is in the wrong scope and I cannot get it one level up to be with ID to generate an ID with each set of video.
I am looking for something that will give me this query result:
{
"data": {
"allVideo": {
"edges": [
{
"node": {
"id": "6b3cddf43cce8f8a0fb122d194db6edc",
"data": [
{
"title": "vid 1",
"url": "url1"
}
]
}
},
{
"node": {
"id": "some other ID",
"data": [
{
"title": "vid 2",
"url": "url 2"
}
]
}
}
]
}
}
}
You can do this by querying a single video using the GraphQL query below.
If you check the docs on GraphQL playground on http://localhost:8081/___explore you should see a query for Video and also allVideo. Instead of using allVideo in your vue components use a single video and pass in the ID you should get the result you want.
{
Video(id: "6b3cddf43cce8f8a0fb122d194db6edc") {
edges {
node{
id
data {
title
url
}
}
}
}
}

parse JSON coming from a REST service in a React Native app

I need help to parse the following JSON coming from a REST service.
I want to read into an array and further each item I have to display on a mobile screen.
[
{
"Login":
{
"Status": "Success",
"nm_vw": {
"EMPLID": "88888",
"NAME": "sample test"
}
}
}
]
You can access data like:
let data=[
{
"Login":
{
"Status": "Success",
"nm_vw": {
"EMPLID": "88888",
"NAME": "sample test"
}
}
}
];
to access status use:
console.log(data[0]['Login']['Status']);
to read emplid:
console.log(data[0]['Login']['nm_vw']['EMPLID']);

Google Assistant not showing basic card when responding to action_intent_PERMISSION

I have two intents defined on Dialogflow. Both use a webhook fulfillment implemented in php which returns json.
One of them is activated by the action_intent_PERMISSION event. If the user granted permission, it performs an action and returns both SimpleResponse (text) and a Basic Card with some text and an image.
The problem is that the Basic Card is never shown. In the debug tab of Google Actions Simulator, I can see that the Basic Card is present in the json sent to the assistant, I see it in the Response tab in simulator, but if I look at the Debug tab in simulator, the basic card is not listed under visualElementsList.
The other intent asks user for a zip code, and then performs the same action and returns the same json as the previous intent. In this case, the Basic Card is always shown and I can see it listed under visualElementsList in the Debug tab.
I can't find why the basic card is not displayed at all when the intent is activated by the action_intent_PERMISSION event. I have been researching and looking and can't find it. Thank you for any help.
This is the response tab in simulator for the intent that shows the basic card:
{
"conversationToken": "[\"closestitem\"]",
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "The item is xxxxx"
}
},
{
"basicCard": {
"title": "Your Closest Item",
"subtitle": "The item is XXXX XXXX XXXX",
"image": {
"url": "https://www.example.com/image.jpg",
"accessibilityText": "Item"
},
"buttons": [
{
"title": "View More",
"openUrlAction": {
"url": "https://www.example.com/"
}
}
]
}
}
]
}
},
"responseMetadata": {
"status": {
"message": "Success (200)"
},
"queryMatchInfo": {
"queryMatched": true,
"intent": "XXXXXXX-2fd7-4ec3-9c88-d90cfccf8661",
"parameterNames": [
"zip"
]
}
}
}
This is the content of the response tab for the intent that is not showing the basic card. I need this basic card to be shown:
{
"conversationToken": "[\"closestitem\",\"closestitem-followup\"]",
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "The item is XXXXXX"
}
},
{
"basicCard": {
"title": "Your Closest Item",
"subtitle": "The item is XXXXXX.",
"image": {
"url": "https://www.example.com/image.jpg",
"accessibilityText": "Item"
},
"buttons": [
{
"title": "View More",
"openUrlAction": {
"url": "https://www.example.com/"
}
}
]
}
}
]
}
},
"responseMetadata": {
"status": {
"message": "Success (200)"
},
"queryMatchInfo": {
"queryMatched": true,
"intent": "XXXXXXX-3c6d-44fa-b35d-6b097c3da054"
}
}
}
The Errors tab is empty in both cases in simulator.

Use Apps Script URLFetchApp to access Google Datastore Data

I want to experiment with Google Datastore via Apps Script because I have a current solution based on Google sheets that runs into timeout issues inherent in constantly transacting with Drive files. I've created a test project in Google cloud with a service account and enabled library MZx5DzNPsYjVyZaR67xXJQai_d-phDA33
(cGoa) to handle the Oauth2 work. I followed the guide to start it up here and got all the pertinent confirmation that it works with my token (and that removing the token throws an 'authentication failed prompt').
Now I want to start with a basic query to display the one entity I already put in. I can use the API Explorer here and run this query body:
{
"query": {}
}
and get this result:
{
"batch": {
"entityResultType": "FULL",
"entityResults": [
{
"entity": {
"key": {
"partitionId": {
"projectId": "project-id-5200707333336492774"
},
"path": [
{
"kind": "Transaction",
"id": "5629499534213120"
}
]
},
"properties": {
"CommentIn": {
"stringValue": "My First Test Transaction"
},
"Status": {
"stringValue": "Closed"
},
"auditStatus": {
"stringValue": "Logged"
},
"User": {
"stringValue": "John Doe"
},
"Start": {
"timestampValue": "2017-08-17T18:07:04.681Z"
},
"CommentOut": {
"stringValue": "Done for today!"
},
"End": {
"timestampValue": "2017-08-17T20:07:38.058Z"
},
"Period": {
"stringValue": "08/16/2017-08/31/2017"
}
}
},
"cursor": "CkISPGogc35whh9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"version": "1503004124243000"
}
],
"endCursor": "CkISPGogc35wcm9qZWN0LWlkLTUyMDAxxDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"moreResults": "NO_MORE_RESULTS"
}
}
I try to do the same thing with this code:
function doGet(e)
{
var goa = cGoa.GoaApp.createGoa('Oauth2-Service-Account',
PropertiesService.getScriptProperties()).execute(e);
if(goa.hasToken()) {var token = goa.getToken();}
var payload = {"query":{}}
;
var result = UrlFetchApp.fetch('https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
method: "POST",
headers: {authorization: "Bearer " + goa.getToken()},
muteHttpExceptions : true,
payload: payload
});
Logger.log(result.getBlob().getDataAsString());
}
and get this error in the logger:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
If I try to use another word such as 'resource' or 'GqlQuery', I get this error:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message."
}
]
}
]
}
}
I can't tell from the API Documentation what my syntax is supposed to be. Can anyone tell me how to compile a functional request body from Apps Script to Datastore?
You need to set the contentType of your payload as well as stringify your JSON payload as follows:
var result = UrlFetchApp.fetch(
'https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
'method':'post',
'contentType':'application/json',
'headers': {authorization: "Bearer " + goa.getToken()},
'payload':JSON.stringify(payload)
}
);

angularJS $resource response is both array AND object

got this json file:
[
{
"name": "paprika",
"imgSrc": "img/paprika.jpg"
},
{
"name": "kurkku",
"imgSrc": "img/kurkku.jpg"
},
{
"name": "porkkana",
"imgSrc": "img/porkkana.jpg"
},
{
"name": "lehtisalaatti",
"imgSrc": "img/lehtisalaatti.jpg"
},
{
"name": "parsakaali",
"imgSrc": "img/parsakaali.jpg"
},
{
"name": "sipula",
"imgSrc": "img/sipuli.jpg"
},
{
"name": "peruna",
"imgSrc": "img/peruna.jpg"
},
{
"name": "soijapapu",
"imgSrc": "img/soijapapu.jpg"
},
{
"name": "pinaatti",
"imgSrc": "img/pinaatti.jpg"
}
]
Which I successfully fetch in a factory:
factory('getJson', ['$resource', function($resource) {
return $resource('json/vegs.json', {}, {
query: {method:'GET', isArray:true}
});
}]);
in my Controller I can get the json's file content:
var vegs = getJson.query();
$scope.vegs = vegs;
console.log(vegs)
console.log(typeof vegs)
The weird part is the first console.log produces an array of objects, as expected.
The second console says it's an "object", and not an array.
I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.
I'm breaking my head on this for over 3 hours now :)
This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).
Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".
There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray