0

So I have this json data that contains strings \r (carriage return) and \n (new line) - It's from Firebase. The problem is when I encode the data using json.encode it add an escaping character. So \r becomes \\r. I'm sending that data to an another server. json.encode works as expected if I do json.encode({'hello': 'world\r\n'}) but it adds \ when I used it on my other string.

Am I missing something? Is there some type of encoding to prevent it from adding \?

3
  • 1
    It sounds like your JSON data does not contain carriage return and newline characters but contains the literal character sequences '\', 'r' and '\', 'n'. Commented Feb 23, 2022 at 4:18
  • It does contains character literal since Firebase only support that. Would a replace all \r with \r do the trick? Commented Feb 23, 2022 at 4:21
  • 1
    what is the problem with the escaped JSON data? When you decode it'll be removed automatically. There is no such harm. Commented Feb 23, 2022 at 4:46

1 Answer 1

1

It seems that the data you received does not contain CR and LF characters but contains their escape sequences (\ followed by r and \ followed by n). Therefore when you encode that to JSON, it will be escaped again.

You could do:

data = data.replaceAll('\\r', '\r').replaceAll('\\n', '\n');

which probably would work most of the time, but it would have the corner case of undesirably replacing occurrences that were explicitly intended to be escaped. (That is, a string '\\n' would be transformed to a sequence \, LF.)

Since the data is already escaped, you probably could unescape it with json.decode. Of course, decoding the data as JSON just to re-encode it to JSON seems a little silly, so if it's already properly encoded JSON, you ideally should pass it through it unchanged.

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

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.