0

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

e.g

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?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Bhavin Hirpara
  • 336
  • 1
  • 9

2 Answers2

0

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"} });

HatzavW
  • 560
  • 1
  • 4
  • 16
  • Thanks for answer. I checked that error is not from server. I am passing json stringified data from server .

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

    This wont work because stringJson has to be parsed in json object. and i am doing operation in script tag.
    – Bhavin Hirpara Apr 06 '17 at 11:04
  • maybe this can help: http://stackoverflow.com/questions/28603658/can-a-js-script-get-a-variable-written-in-a-ejs-context-page-within-the-same-fil – HatzavW Apr 06 '17 at 12:17
0

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);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175