I am going to create a simple encryption server using API Gateway and Lambda provided by AWS.
API Gateway telecommuted the HTTP API method, which supports Payload 2.0 version of Payload.
An example of this Payload is as follows.
{
"version": "2.0",
"routeKey": "$default",
"rawPath": "/my/path",
"rawQueryString": "parameter1=value1¶meter1=value2¶meter2=value",
"cookies": [
"cookie1",
"cookie2"
],
"headers": {
"header1": "value1",
"header2": "value1,value2"
},
"queryStringParameters": {
"parameter1": "value1,value2",
"parameter2": "value"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "api-id",
"authentication": {
"clientCert": {
"clientCertPem": "CERT_CONTENT",
"subjectDN": "www.example.com",
"issuerDN": "Example issuer",
"serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
"validity": {
"notBefore": "May 28 12:30:02 2019 GMT",
"notAfter": "Aug 5 09:36:04 2021 GMT"
}
}
},
"authorizer": {
"jwt": {
"claims": {
"claim1": "value1",
"claim2": "value2"
},
"scopes": [
"scope1",
"scope2"
]
}
},
"domainName": "id.execute-api.us-east-1.amazonaws.com",
"domainPrefix": "id",
"http": {
"method": "POST",
"path": "/my/path",
"protocol": "HTTP/1.1",
"sourceIp": "IP",
"userAgent": "agent"
},
"requestId": "id",
"routeKey": "$default",
"stage": "$default",
"time": "12/Mar/2020:19:03:58 0000",
"timeEpoch": 1583348638390
},
"body": "Hello from Lambda",
"pathParameters": {
"parameter1": "value1"
},
"isBase64Encoded": false,
"stageVariables": {
"stageVariable1": "value1",
"stageVariable2": "value2"
}
}
In this Payload, the data I want to parse and utilize with json is a body value.
The test provided by Lambda itself proceeds without any problems, but when a request is sent by postman in the application/json method, the body is included in the payload in a string format that cannot be parsed into json.
An example is as follows.
"[\r\n {\r\n \"key\" : \"aaa\",\r\n \"value\" : \"value1\"\r\n },\r\n {\r\n \"key\" : \"bbb\",\r\n \"value\" : \"value2\"\r\n }\r\n]"
The original body value is like this.
[
{
"key" : "aaa",
"value" : "value1"
},
{
"key" : "bbb",
"value" : "value"
}
]
The language I will use when parsing to json is JavaScript.
What should I do for parsing this "Stringify Data" to JSON??
CodePudding user response:
Your string can be converted to JSON using JSON.parse()
var data = "[\r\n {\r\n \"key\" : \"aaa\",\r\n \"value\" : \"value1\"\r\n },\r\n {\r\n \"key\" : \"bbb\",\r\n \"value\" : \"value2\"\r\n }\r\n]"
console.log(JSON.parse(data))