6

I have problem with returning string from Lambda after

JSONObject.toString

in return i have

"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}" 

instead of

"{"Key2":"Value2","Key1":"Value1"}"

Can somebody explain how to exclude these slashes?

2
  • What does this have to do with AWS or Lambda ? Commented Dec 6, 2017 at 14:21
  • It is just because the string is returned from a Lambda, I assumed, using AWS. Commented Dec 7, 2017 at 7:48

3 Answers 3

1

If you really need to remove them ...

yourstring.replace("\\", "");

However, those "stupid slashes" are necessary if you are treating your response as a string, as they escape your " character. Specifically, without those, your compiler would behave as such:

"{"     // is a string
Key2    // Not known by Java
":"     // is a string
Value2  // Not known by Java
","     // is a string
Key1    // Not known by Java
":"     // is a string
Value1  // Not known by Java
"}"     // is a string

By escaping your " character with a backslash, you are mentionning to your compiler that it should not be taken as an end of string nor a begin. Thus, asking it to only take in account the first and last ".

Sign up to request clarification or add additional context in comments.

Comments

1

Don't serialize your object in your project. AWS Lambda will handle object serialization for you as mentioned here. Just return an object!

e.g.

//return type is an object not a string
public SomeObject handleRequest(Object input, Context context) {
...
}

Comments

0

I've done similar to this before in JavaScript. If you don't serialize the object at all, then AWS API Gateway should take care of it for you. If your Lambda returns something like this:

// ...
context.done(null, {
    id: i.id,
    last_name: i.last_name,
    gender: i.gender
});

...then your API response will look something like this:

{
    "id": 1,
    "first_name": "Chris",
    "gender": "male"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.