-2

I can't find the equivalent of the escape method that exists for java here https://www.tutorialspoint.com/json_simple/json_simple_escape_characters.htm

text = jsonObject.escape(text);

in javascript ?

user310291
  • 36,946
  • 82
  • 271
  • 487
  • 2
    `JSON.stringify()`? – Phil Feb 17 '21 at 22:54
  • That is a strange method. The documentation says *"The following characters are reserved characters and can not be used in JSON...`JSONObject.escape()` method can be used to escape such reserved keywords in a JSON String."*. If you have a JSON string, then how could you ever have reserved characters in it, as that would make it NOT a JSON string in the first place... – trincot Mar 10 '21 at 18:47

1 Answers1

0

The documentation you refer to, gives this Java example:

Example

import org.json.simple.JSONObject;

public class JsonDemo {
   public static void main(String[] args) {
      JSONObject jsonObject = new JSONObject();
      String text = "Text with special character /\"\'\b\f\t\r\n.";
      System.out.println(text);
      System.out.println("After escaping.");
      text = jsonObject.escape(text);
      System.out.println(text); 
   } 
} 

Output

Text with special character /"'
. 
After escaping. 
Text with special character \/\"'\b\f\t\r\n. 

The same can be achieved in JavaScript as follows:

let text = "Text with special character /\"\'\b\f\t\r\n.";
console.log(text);
console.log("After escaping.");
text = JSON.stringify(text).slice(1, -1); // Encode and remove the wrapping double quotes.
console.log(text);

There is one difference in the output: the JSON.simple Java library escapes the forward slash, JavaScript's JSON.stringify doesn't.

JSON does not require the slash to be escaped. Note also that the above mentioned documentation does not list it as a "reserved character", so JSONObject.escape() escapes a bit more than is essential (but it doesn't hurt).

trincot
  • 317,000
  • 35
  • 244
  • 286