Getting an error while sending a json payload in quartz scheduler - json

I'm trying to send a json payload in quartz scheduler. I have the header set to Content-type:application/json, but for some reason my json string is throwing an error: Uncaught error, unexpected token in json.
The original json that I'm sending to a graphql service looks like this:
{
GetAllAuthors{
id
name
}
}
But to make it work in quartz, I need to mimic a rest API call, which is why I tried using the following:
{ "query":{{""{\nGetAllAuthors {\nid\nname\n}\n\n}""}} }
The above is also giving me the "Uncaught error, unexpected token in json" error. Is there something that I'm missing or overlooking?
PS: I tried using an online json formatter and when I try to validate the above json, I get the following error:
Error: Parse error on line 2:
{ "query": { { "" {\ nGetA
--------------^
Expecting 'STRING', '}', got '{'

That's not valid Json. This is how it might look if it were:
{
"GetAllAuthors": [
"id",
"name"
]
}
but I suspect you're trying for something like this:
{
"GetAllAuthors": {
"id": 123,
"name": "James Brown"
}
}
Play here until you get it right: https://jsonlint.com/
Edit: I've not worked with GraphQL, but this page shows how a (non JSON) GraphQL query might be transferred over Http by POSTing JSON or GETting using querystrings: https://graphql.org/learn/serving-over-http/

I figured this out by testing through Mozilla's network tab - the correct format is:
{"query":"{\n GetAllAuthors{\n id\n name\n}\n}\n","variables":null, "operationName":null}

Related

How to parse dynamic json reponse and get specific value and pass it as an input to next request

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")))

Json.net JObject.Parse erroring on complex json

The following code:
let resp = string(argv.GetValue 0)
let json =JObject.Parse resp
gives this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Input string '2.2.6' is not a valid number.
Path 'items[0].versionName', line 1, position 39.
where argv is this input:
{
"totalCount":1,
"items":[
{
"versionName":"2.2.6",
"phase":"PLANNING",
"distribution":"EXTERNAL",
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versionReport",
"href":"url"
},
{
"rel":"project",
"href":"url"
},
{
"rel":"policy-status",
"href":"url"
}
]
}
}
]
}
How can I fix this? Is there a simple way to implement a json reader that does not error here?
I also get this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Error parsing undefined value. Path 'items[0].name', line 1, position 28.
With this input:
{
"totalCount":1,
"items":[
{
"name":"uaa",
"projectLevelAdjustments":true,
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versions",
"href":"url"
},
{
"rel":"canonicalVersion",
"href":"url"
}
]
}
}
]
}
I am trying to read in json of many different schemas that I did not make or know. The first error seems to be because it is trying to generate a float from something that should be output as a string. The second sounds like the schema is too complex and a type would be needed to properly parse it using Json.Deserialize but I'm not sure how to do that and it would take too much time as there are too many schemas to make a types for them all. Is there any way around both these things?
In C# you can use dynamic with something like this:
var json = JsonConvert.DeserializeObject(resp)
And then you could access properties with something like: json.totalCount.
In F# land, this question gives some suggestions for how you might deal with dynamic objects. If you use the package FSharp.Interop.Dynamic you can get the value of totalCount in your example with something like this:
let value:obj = json?totalCount?Value
which gives 1L on my computer.

Could not parse request body into json: Unexpected character (\'-\' (code 45)) AWS Lambda + API + Postman

I have been trying for a few days to get a parameter sent from the API Gateway in AWS to a Lambda function and I am having no success.
I decided to start from the beginning so I followed their walkthrough (http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started.html#getting-started-new-lambda)
I have checked this walkthrough twice and I have followed the steps to the letter.
Problem
When I test the API from Postman or in Swift I am getting the error:
{"message": "Could not parse request body into json: Unexpected character (\'-\' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value\n at [Source: [B#c036d15; line: 1, column: 3]"}
In postman, When I view the result as JSON I just get
Bad String
Lambda Function
The function is the basic example from the Walkthrough:
console.log('Loading event');
exports.handler = function(event, context) {
var name = (event.name === undefined ? 'No-Name' : event.name);
console.log('"Hello":"' + name + '"');
context.done(null, {"Hello":name}); // SUCCESS with message
};
When Tested from the Lambda Console and with the Test data I get the result:
{
"Hello": "TestUser123"
}
When Tested from the API Gateway Test, The result is also:
{
"Hello": "TestUser123"
}
Can anyone see why both test consoles are allowing this work but when tested with POSTMAN or used within a Swift Script it does not work ?
Edit 1
In postman, I have set the content-type to application/json
The script returns the default:
{
"Hello": "user"
}
However, When I add in the parameters name and TestUser123 in POSTMAN, this is when it returns the error.
Update 1
Ok, so I changed the mapping template to one that I found on another answer:
{ "name": "$input.params('name')" }
Now the result is:
{
"Hello": ""
}
Any Ideas why it is not getting the name?
I just got stuck with this today.
your mapping template is:
{ "name": "$input.params('name')" }
AWS uses AWS Velocity templates, which; even though looks like JSON, is different.
if you use
{ "name": $input.params('name') } // notice no quotes
for the mapping template right at the integration request step, then it should work as expected.
Read the error message very carefully, it actually tells you the problem. For example, I got
Could not parse request body into json: Unexpected character (\'\"\' (code 34)): was expecting comma to separate Object entries
So the problem is that I'm missing a comma. I check my Lambda's Integration Request - Body Mapping Template:
{
"age" : $input.json('$.persondata.age'),
"income" : $input.json('$.persondata.income')
"height" : $input.json('$.persondata.height')
}
Can you spot the problem? I am missing a comma after the income line.
Here is another example.
Could not parse request body into json: Unexpected character (\'}\' (code 125)): expected a value
When I look at the Integration Request - Body Mapping Template:
#set($inputRoot = $input.path('$'))
{
"age" : $inputRoot.age,
"height" : $inputRoot.height,
"income" : $inputRootincome
}
Can you spot the problem? I am missing a dot in $inputRootincome.
Error Message :
Could not parse request body into json: Could not parse payload into json: Unrecognized token \' \': was expecting (\'true\', \'false\' or \'null\')
Cause of the error : When string values inside the json are not assigned using double quotations in the aws mapping template the error occurs.
Solution : (Please Note : This example is for application/json type request template)
Actually the solution for the problem is, if you are using a value of type string in json then its value should be assigned inside a ("" - double quotation marks) in the mapping template.
The below shown example has the following attributes :
customerId - string (Please note : this value comes from a query parameter)
customerName - string
customerAge - integer
isPermanentEmployee - boolean
customerAddress - string (Please note this is an optional parameter)
And the mapping template should be defined like the example shown below
Refer the example below :
#set($inputRoot = $input.path('$'))
{
"CustomerId": "$input.params('customerId')",
"CustomerName": "$inputRoot.customerName",
"CustomerAge": $inputRoot.customerAge,
"IsPermanentEmployee": $inputRoot.isPermanentEmployee
"CustomerAddress ": #if($inputRoot.customerAddress == "") "" #elseif($inputRoot.customerAddress != "") "$inputRoot.customerAddress" #end
}
If you note the above mapping template, I would have given string values inside double quotation marks("") which will solve the error
Also this example contains how to handle optional parameters in aws mapping templates using #if#else statements.
It is likely that you had copy-pasted multiple lines in your "Integration Request" in the API gateway.
When copying a line and pasting it below, you might have copied the hidden character '\n' at the end of that line. This is probably causing issues at the lambda function.
Example: Copying the line containing age and pasting it twice and modifying them to have height and income respectively.
#set($inputRoot = $input.path('$'))
{
"age" : $inputRoot.age,
"height": $inputRoot.height,
"income": $inputRoot.income
}
Instead of copy-pasting, just type the line out for height and income.

POST json object to REST server via Postman

I am getting an error while sending a json object to server. My json object is as follows:
{
"AppVersion": "2.0",
"connection": "3G",
"received": "2015-10-30",
"smsContent": "test string",
"msisdn": "923453334444"
}
When I send request, I am getting this error:
Malformed JSON: Unexpected 'c'
What is wrong with my json object? Can someone help here?
This may be due to the incorrect syntax of your code. I also got this error and corrected by eliminating unnecessary semicolons from my code.

apigee 127 - JSON is escaped when ran in mock mode

I'm guessing I've missed something silly so I apologize in advance.
I'm trying to run the example found at the following URL in mock mode: https://github.com/apigee-127/a127-samples/blob/master/weather-basic/api/swagger/swagger.yaml
The JSON response looks like it's being escaped and it's causing the response validator to fail:
{
"message": "Response validation failed: invalid content type (text/plain). These are valid: application/json",
"failedValidation": true,
"originalResponse": "{\"base\":\"Sample text\",\"clouds\":{\"all\":1},\"cod\":1,\"coord\":{\"lat\":1,\"lon\":1},\"dt\":1,\"id\":1,\"main\":{\"humidity\":1,\"pressure\":1,\"temp_max\":1,\"temp_min\":1,\"temp\":1},\"name\":\"Sample text\",\"sys\":{\"country\":\"Sample text\",\"id\":1,\"message\":1,\"sunrise\":1,\"sunset\":1,\"type\":1},\"weather\":[{\"description\":\"Sample text\",\"icon\":\"Sample text\",\"id\":1,\"main\":\"Sample text\"}],\"wind\":{\"deg\":1,\"speed\":1}}"
}
Any ideas would be awesome!
You need to send something like this res.json({});
Send as json object don't stringify your result object ,
var result = {name:"asdf",id:1212}
res.json(result);