I have an AppSync GraphQL API that makes a Query to a DynamoDB and returns a JSON String, however in my Response Mapping Template I use the built-in $util.parseJson()
function as listed here - but I'm still returned a JSON string in the Query window and when requesting the data in my React app.
Schema file, I have an ordinary ID & Address field that is of type AWSJSON.
type Venue {
id: ID!
address: AWSJSON
}
When running a mutation, I usually run the address object through a quick JSON.stringify(addressObj)
and that formats the object as a string with the \"\" escaped, meaning that it can be inserted into DynamoDB.
Request Mapping template
{
"version": "2017-02-28",
"operation": "GetItem",
"key": {
"id": $util.dynamodb.toDynamoDBJson($ctx.args.id),
}
}
Response Mapping template
#set($result = $ctx.result)
## address - parse back to JSON
#set($result.address = $util.parseJson($ctx.result.address))
## Return the result
$util.toJson($result)
The idea to create a new variable and then assign the value to the parseJSON
value was taken from How return JSON object from DynamoDB with appsync?. So, as seen below, I am parsing the value through what seems to be the correct method to turn it from stringified JSON, to an object - but it doesn't appear to work.
The current response:
{
"data": {
"getVenue": {
"id": "31538150",
"address": "{\"lng\":-1.54511300000001,\"postcode\":\"LS1 5DL\",\"short\":\"New Station St., LS1\",\"lat\":53.795231,\"full\":\"16 New Station St, Leeds LS1 5DL, UK\"}"
}
}
}
Whereas the response that I am wanting is...
{
"data": {
"getVenue": {
"id": "31538150",
"address": { "lng": -1.54511300000001, "postcode": "LS1 5DL", "short": "New Station St., LS1", "lat": 53.795231, "full": "16 New Station St, Leeds LS1 5DL, UK" }
}
}
}
Any help is greatly appreciated!
AWJSON
represents aJSON string
. It also says thatthey will automatically be parsed and loaded in the resolver mapping templates as Maps, Lists, or Scalar values rather than as the literal input strings.
– Lisa M Shonaddress
more times than you intended. A temporary test to confirm this might be#set($result.address = $util.parseJson($util.parseJson($ctx.result.address)))
– Michael - sqlbot