How to pass a JSON string to API Gateway as query Parameter - json

How can i pass a JSON object like {val: 1} to my Lambda function as a query parameter?
Following Standardized way to serialize JSON to query string? i URL-encoded my JSON object and requested the following: mysite.com/path?json=%7B%22val%22%3A%201%7D
As requestTemplates i tried the following two options
"json": "$input.params().querystring.json"
"json": "$util.parseJson($input.params().querystring.json)"
But i got this error message:
{"message": "Could not parse request body into json: Unexpected
character (\'v\' (code 118)): was expecting comma to separate OBJECT
entries\n at [Source: [B#37a2970e; line: 1, column: 47]"}
If i do not encode the query string so: mysite.com/path?json={"val":1} i get a 400 error

Your mapping template is producing no valid JSON, you have to wrap the key/value pair in curly braces
I guess you do not want to wrap the value in quotes, it will be a string and no object otherwise
You can use $util.urlDecode to decode URL encoded strings
Your mapping template should look like this:
{"json": $util.urlDecode($input.params().querystring.json)}
For mysite.com/path?json=%7B%22val%22%3A%201%7D this mapping template will result in the following JSON:
{
"json": {
"val": 1
}
}
If you want the querystring JSON to be passed on the root level to your Lambda function use this as a mapping template:
$util.urlDecode($input.params().querystring.json)

Related

JSONPath: Get field starting with # in escaped json string

I want to get a nested field in a json string using JSONPath.
Take for example the following json:
{
"ID": "2ac464eb-352f-4e36-8b9f-950a24bb9586",
"PAYLOAD": "{\"#type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
}
If I want to extract the #type field, I expect to do it like this
$.PAYLOAD.#type
But that doesn't seem to work..
Also tried this:
$.PAYLOAD['#type']
Do I need to use escape chars or something?
Posting my comment as an answer
"{\"#type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
Isn't JSON, it's a string containing encoded JSON.
Since JsonPath can't decode such string, you'll have to use a language of your desire to decode the string.
Eg: Decoding JSON String in Java

How do I correctly deserialize json that consists of a list item that includes another object?

The client I am using returns json like this:
[
{
"source": "ANY"
}
]
That is, the element of the array that the object is in.
I'm trying to make a request like this:
restTemplate.postForObject<AbcdResponse>(
"/address",
listOf(value).let { JsonHttpEntity(it) }
)
data class AbcdResponse(
val obj: AbcdObject
)
data class DaDataAddress(
val source: String?
)
But I get the HttpMessageNotReadableException exception:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token
at [Source: (ByteArrayInputStream); line: 1, column: 1]
How can I deserialize the response correctly?
As you probably noticed, the response as a whole is a JSON array. You can tell by the square brackets [ ... ] surrounding the whole thing.
Because of this, you cannot deserialize it as an object (such as AbcdResponse). What you should do instead is use List<DaDataAddress> instead of AbcdResponse.
You don't really need AbcdResponse. What you need is to use a ParameterizedTypeReference as follows while calling the service:
restTemplate.exchange("/address",
HttpMethod.POST,
listOf(value).let { JsonHttpEntity(it) },
ParameterizedTypeReference<List<DaDataAddress>>() {})
The reason is that the service that you are calling is returning a JSON array of JSON objects.

JSON Object Parse

exercise question screenshot
Not sure what's missing. The other discussion solutions seem too complicated compared to my homework question:
Q:
-The variable str_json has been assigned a string of a JSON object
-Call the parse method, pass it str_json and assign the return value to variable jsonobj
-Assign the property the_city to the variable v_the_city
-Assign the property stateval to the variable v_stateval
var str_json = {'v_the_city':'the_city','v_stateval':'stateval'};
var jsonobj = JSON.parse(str_json);
SyntaxError:
the JSON dataJSON.parse: unexpected character at line 1 column 2 of
SyntaxError: unexpected token: identifier
str_json should be a JSON string, not an object.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. Read more here, link.
Syntax:
JSON.parse(text[, reviver])
Parameters:
text - The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver - [Optional] If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

Handle raw JSON string with node and express

I have a really simple endpoint defined in NodeJS using Express:
router.put("/test", this.test.bind(this));
public test(req: Request, res: Response, next: NextFunction) {
console.log(req.body);
}
The endpoint is working correctly if I PUT the following JSON body:
{
"name": "something"
}
However, if I use a JSON body without curly brackets (which is totally valid) like this:
"something"
I get an error:
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:558:11)
Content-Type in both cases is application/json.
Why are these raw JSON strings not getting accepted and how can I solve this?

How to access a string path param in a in API Gateway for AWS

So I have something like
my/path/123
And this works fine.
However, when I try with a string "asdf"
my/path/"asdf"
I get this
{"message": "Could not parse request body into json: Unexpected character (\'%\' (code 37)): expected a valid value (number, String, array, object, \'true\', \'false\' or \'null\')\n at [Source: [B#420db2ef; line: 2, column: 13]"}
And if I try w/o quotes (so my/path/asdf) I get this:
{"message": "Could not parse request body into json: Unrecognized token \'asdf\': was expecting (\'true\', \'false\' or \'null\')\n at [Source: [B#7fba20c8; line: 2, column: 17]"}
And if I try https://7mdamwt4jg.execute-api.us-east-1.amazonaws.com/prod/%22asdf%22
(%22 is stands for double quotes)
I get this:
{"message": "Could not parse request body into json: Unexpected character (\'%\' (code 37)): expected a valid value (number, String, array, object, \'true\', \'false\' or \'null\')\n at [Source: [B#7f4f2919; line: 2, column: 13]"}
What else can I try?
You can create a body mapping template in integration request and get path param like below,
{
"PathName" : "$input.params('PathName')"
}
Where 'PathName' is the name of your path param.
Say your path name is UserId then you can get params inside Lambda function like an event.UserId. Please see below screenshots to get into body mapping template,
This error indicates that your Lambda function cannot parse request string into json. The problem is most likely to be in your mapping template. See working example here https://gist.github.com/rpgreen/5cd3d5c872781335a5d3