Reputation: 973
I have problem to convert back json string containing double quote to javascript object in JSON.parse()
. Here is details below.
I have a object saved in variable groupdata
in nodejs app.js
[{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New\" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]
In my nodejs app.js code, groupdata object is passed to client as a json string.
function doRender() {
res.render('groupdata', {
'groupdata': JSON.stringify(groupdata)
});
}
My client code tries to prevent XSS attack first by function htmlDecode()
then JSON.parse()
a valid json string to object.
JSON.parse(test1)
will succeed if only the string does not contain double quote.
JSON.parse(test2)
will fail as error below
function htmlDecode(input){ //prevent XSS attack;
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
console.log('groupdata: ' + "<%= groupdata %>");
var test1 = htmlDecode("<%= (groupdata) %>");
console.log('test1: ' + test1);
var test2 = htmlDecode("<%= JSON.stringify(groupdata) %>");
console.log('test2: ' + test2);
JSON.parse(test1); // Succeed if only test1 value contains no double quote
JSON.parse(test2); // ERROR: Uncaught SyntaxError: Unexpected token _
The console log in client chrome browser:
groupdata: [{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]
test1: [{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]
test2: "[{"_id":"56adb85319dec52455d11c21","fullName":"NY Metro Office 365 What New\" group","createdAt":"2015-08-25T17:03:59.000Z","stats":{"members":65}}]"
Question: How can I convert json string with double quote to javascript object in this case?
Upvotes: 1
Views: 1838
Reputation: 973
It turns out that EJS has its own way to htmlescape to protect from XSS attack
<script type="text/javascript">
var groupdata = <%- JSON.stringify(groupdata); %>
</script>
This is simple and clean. Thanks to @migg again for his commenting.
Upvotes: 2