简体   繁体   中英

Json parse() does not escape \" in javascript

I have java object which is converted as JSON string using

    String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap()); 
    model.addAttribute("testTypeMap", paramMap );

In the .jsp page, on load I'm trying to parse the testTypeMap and get object back;

    var paramMap = JSON.parse('${testTypeMap}');
    showTestType('File content', 'LINUX', paramMap);    

The object has double quotes (") in one of the fields, and it is escaped with backslash () when it is converted as JSON sting in java, that is why we see "\\"" (from view source)

    var paramMap = JSON.parse('{"Filepath":"/home/status.txt","Search expression":"\""}');

But the above line says, "Uncaught SyntaxError: Unexpected string".

I have seen few posts and they say it need two parses, one for javascript and one for JSON. I tried to replace \\" with \\\\" ; but in javascript \\" is always ", so I could not replace it;

Any pointer for what I miss here?

The problem is that you're not encoding the string in ${testTypeMap} as a JavaScript literal. I'm unsure how to do it specifically in your framework, but it's akin to HTML encoding a string, but for JavaScript instead.

However!

In your specific example you can avoid using JSON.parse because JSON is already in a format consumable by JavaScript.

var paramMap = ${testTypeMap};
showTestType('File content', 'LINUX', paramMap);

With the resulting source sent to browser looking like:

var paramMap = {"Filepath":"/home/status.txt","Search expression":"\""};

Actually I was not knowing how to replace \\" with \\\\" in javascript, as \\" is always represented as " (just one quote without backslash).

So I did this replace in server side after converting to a JSON string using Jackson's ObjectMapper as below:

   String paramMap = new ObjectMapper().writeValueAsString(custPolicy.getParamMap()); 
   // need to replace any \" with \\" in javascript side
   paramMap = paramMap.replace("\\\"", "\\\\\""); 
   model.addAttribute("testTypeMap", paramMap );

Now in client-side it shows as below:

   var paramMap = JSON.parse('{"Filepath":"/home/cavirin/status.txt","Search expression":"\\""}');

and this works fine as javascript parse is already taken care in server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM