简体   繁体   中英

Not able to parse json string in ejs becuase of single quote in value

I am passing one json string variable from nodejs to ejs.

eg

stringJson = "{"obj" : "it's not working"}"

I am retrieving this value on ejs inside script tag using var stringifiedJson = '<%- stringJson%>'

so when page is being rendered it is giving error "SyntaxError: missing ; before statement" because stringJson value contain single quote.

I came across some solution like i can replace it single quote with "'" but problem in this solution i am passing many jsonString variables from node to ejs. so i have do same in all variables.

I also seen in some solution like below

<script>
    var stringifiedJson = <%- stringJson%>
</script>

without surrounding ' '. but its showing error "expression require" error.

is there any other way with i can parse jsonString to Json object?

Something like that will work:

<p>stringJson.obj: <%= stringJson.obj %></p>

I think the error come from the server response, try this:

res.render('index.ejs', { stringJson: {"obj": "it's not working"} });

在客户端使用其他引号,如 `` 或 ''

The problem you face is caused by the fact that there are quotes inside the text that you have. A very easy solution is to escape your value on server-side and unescape it on the client-side, assigning the result to your variable.

Alternatively (but not advisably) you could base64 the text at your server-side and decode it as below:

 let result = atob('eyJvYmoiIDogIml0J3Mgbm90IHdvcmtpbmciLCAic29tZSBjb2RlIjogYHNvbWUgdmFsdWVgfQ==') eval('var foo = ' + result); console.log(foo);

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