I have a variable into Google Script for access to data through an API:
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data)
I can run UrlFetchApp.fetch() to access the API without error.
But if I store the variable data into a Google Sheet cell, and read the value like this:
var ticket_data=sheet.getRange('B1').getValue()
JSticket_data=JSON.stringify(ticket_data)
I get this value:
"{ \"header_items\": [{ \"label\": \"Cliente\", \"type\": \"text\", \"item_id\": \"2cba1baf-207c-4529-ab72-7d35363983fc\",\"responses\": {\"text\": \"PRUEBA: ANALISIS FALLA 2\"},},],\"template_id\":\"template_5f9b4f399fe342ce94fefada009ee467\"}"
UrlFetchApp.fetch() does not work correctly with that value.
I think that the problem is when I take the cell data by ticket_data=sheet.getRange('B1').getValue(), it take it as string, and then the JSON.stringify add a double quotes an then add the backslashes. I tried remove the backslash with replaceAll('\\','') but it did not work.
06-10-22
This is an Update after the answer 1 to add more information to my question.
Firs to all Thank you for your answer !! I'm sorry if I shoudn't write this update here. Please tell me where I must to do in the future
I'm sure I making something bad.
I have prepared the variable and parameters for UrlFetchApp as:
ticketJson = work_sheet.getRange('B1').getValue()
var params = {
method:"POST",
contentType:'application/json',
headers:{Authorization:"Bearer "+token},
payload: ticketJson,
muteHttpExceptions:true
};
var post_ticket = UrlFetchApp.fetch("https://api.website.io", params)
Logger.log(post_ticket)
the logger's answer is
Information {"statusCode":400,"error":"Bad Request","message":"Invalid request payload JSON format"}
but if I store the data into a variable and then excecute JSON.stringify() the results is OK.
var ticket_data = { "header_items": [{ "label": "Cliente", "type": "text", "item_id": "2cba1baf-207c-4529-ab72-7d35363983fc","responses": {"text": "PRUEBA: ANALISIS FALLA 2"},},],"template_id":"template_5f9b4f399fe342ce94fefada009ee467"}
JSticket_data=JSON.stringify(ticket_data) // if not excecute this, I get the same error that I tell before
I can't find where is the error Thanks again in advance
Omar
The first code snippet in the question gets a JavaScript object and converts it to a text string with JSON.stringify().
The second code snippet in the question gets a text string that does not need to be processed with JSON.stringify() in order to get a text string. It is a text string.
In other words, you can simply use this:
const ticketJson = sheet.getRange('B1').getValue();
...and use ticketJson as is in UrlFetchApp.fetch().
Related
I'm hitting a wall with this code, where I should extract some Json code within an element attribute. Here is my attempt:
<div labels='[{label: "A", name: "dog"}, {label: "B", name: "cat"}]'></div>
var labels = $("div[labels]").attr("labels");
console.log(data[0].label);
That was my attempt to get just the first object label, but it gives me undefined. I also tried to parse data first but I get some token error in console. What am I exactly missing here? I just want to loop through the objects and for each of them get both label and name.
if your json array keys in qoutes that will work
like this :
[{"label": "A", "name": "dog"}, {"label": "B", "name": "cat"}]
var labels = $("div[labels]").attr("labels");
var data = $.parseJSON(labels);
console.log(data);
OR
var labels = $("div[labels]").attr("labels");
var data = JSON.parse(labels);
console.log(data);
Resolved.
The issue was that keys (label, name) were missing quotes, so it was not correctly parsed.
Resolved by placing
var labels = data_label.attr("labels").replace(/\\n/g, "\\\n").replace(/label/gi, "\"label\"").replace(/name/gi, "\"name\"");
HTML
<div data-labels='[{label: "A", name: "dog"}, {label: "B", name: "cat"}]'></div>
Javascript
jsonObj = eval(document.querySelector("div[data-labels]").dataset.labels)
I am running a chain of collections from 1 API call to another. I want to pull the response body from API call 1 to API call 2 so that it can post the data to my application.
I have created the environment variables and in the tests tab I have created a script to set the variables but when I run the script I get a response of the below:
SyntaxError: Unexpected token [
My test script is:
bodyData = JSON.parse(responseBody)
value = bodyData.[1]country
console.log(value)
The response body looks like this
[
{
"Country": "United Kingdom",
}
]
I know the issue is [] and needs to have a string before it but the API is not defined with a string and I cant just use the below as it's then undefined:
bodyData = JSON.parse(responseBody)
value = bodyData.country
console.log(value)
Any idea how I can get this to work?
You have the reference slightly wrong I think.
This should do it:
let bodyData = pm.response.json()
let country = bodyData[0].Country
console.log(country)
To then set the variable you would need to use:
pm.environment.set("country", country)
I get .json file as a response from an API and from that file I should parse and fins specific parameter and pass it as an input to the next request, how do I do that using Katalon.
If I say
response = JSON.parse("response.json");
it says it is unable to identify JSON as valid. Can someone help me out with the solution?
Your JSON is invalid, maybe it is a copy-paste issue.
The valid JSON should be
{
"responseStatusCode": "OK",
"data": {
"screenName": "employeeTimeslip",
"screenType": "Redirect",
"searchResultCount": 0,
"rows": [],
"tabs": [],
"searchParams": {
"employeeID": "000092926",
"timeslipNumber": "201900019701"
}
}
}
So, you were missing a "," between "OK" and "data" and two closing curly braces at the end of the file.
You can check JSON files for validity yourself using online JSON validators, for example, this one.
i found a way to read specific parameter from the json response file like below:
val scn = scenario("ClaimSubmission")
.exec(http("request_2")
.post("URL")
.headers(headers_2)
.body(RawFileBody("json file path"))
.check(jsonPath("$..timeslipnumber").find.saveAs("timeslipnumber")))
Timeslip number would be retrieved using : .check(jsonPath("$..timeslipnumber").find.saveAs("timeslipnumber")))
I'm trying to make API request with using Apps Script. API is GraphQL based.
I'm using JSON.stringify function. But API returns an error.
Request:
payload={"query":"{mutation {change_column_value (board_id: 177955, item_id: 287466289, column_id:\"phone\", value: \"{phone : 15065332974, countryShortName: \"US\" }\") {name column_values{ id value}}}"}}
I'm getting error;
{"errors":[{"message":"Parse error on \" }\" (STRING) at [1, 148]","locations":[{"line":1,"column":148}]}]}
Apps Script Code:
var us = "US"
var column_values = '{ \
mutation {change_column_value (board_id: 177955, item_id: '+ 287466289 +', column_id:"phone", value: "{phone : 15065332974, countryShortName: \"' + us +'\" }") {name column_values{ id value}} \
}';
settings = {
"method": "POST",
"headers": {"Content-Type" : "application/json","Authorization" : "eyJhbGciOiJIXXXXXXXXXX"},
"payload" : JSON.stringify({query:column_values})
}
response= UrlFetchApp.fetch(url, settings);
Brackets in a GraphQL operation indicate a selection set -- one or more fields that are being requested. The operation itself (whether a query or a mutation) is not a field, so you don't wrap the whole operation in brackets.
Correct:
mutation {
doSomething
}
Incorrect:
{
mutation {
doSomething
}
}
The only time you will see brackets that look like they are on the "outside" is when using query shorthand.
Provided that value is a String, then your use of backslashes to escape the double quotes inside that string should be fine.
You might also consider using variables, which would clean up your code considerably and make it less error prone.
You do not need to escape special characters inside a JSON request.
The syntax implies using key-value pairs assigned to each other with a colon, whereby strings are located inside quotes (not escaped with a backslash!), while numbers and variable names are not.
The brackets should be used in function of your desired API request as documented.
I am trying to write to Firebase from Google Apps Script.
I try this:
var act="https://SampleChat.firebaseIO-demo.com/users/fred/name.json";
UrlFetchApp.fetch(act,{"method":"post","payload":"test"});
and I get this error:
Request failed for https://SampleChat.firebaseIO-demo.com/users/fred/name.json
returned code 400. Truncated server response:
{ "error" : "Invalid data; couldn't parse JSON object, array, or value.
Perhaps you're using invalid characters in your key names." }...
Question
How do I write to Firebase from GAS? (What am I doing wrong?)
Answer
You must stringify the payload object.
Here is a question and answer example.
I tested it and it does work.
Example
function putToFire() {
var payload = '{ "first": "Foo", "last": "Bar" }';
var options = {
"method": "put",
"payload": payload
};
UrlFetchApp.fetch(
"https://SampleChat.firebaseIO-demo.com/users/fred/name.json",
options
);
}
The Key Trick
Notice the single quotes ' around the payload object?
In the following line:
var payload = '{ "first": "Foo", "last": "Bar" }';
That counterintuitive syntax seems to be the trick to making this work. ;-)
Alternative Syntax for Variable Payloads
If your payload is a variable, you can use JSON.stringify():
var payload=JSON.stringify({"first":"Foo","last":"Bar"});