11

I am using EJS with Node.JS, and am passing a JSON object into it, but need to have access to it as a usable object in the page. I am getting the unexpected token o error from this:

var initData=JSON.parse(<%-JSON.stringify(list)%>);

I cant figure out whats wrong here.

This is what it looks like in the file when rendered:

var initData=JSON.parse([{"title":"South Hills Health System - University Health Center","adr":"200 Lothrop St,15213","coords":"40.441875,-79.960813","images":[],"tags":[],"_id":"51c0e9798384f40000000017"},{"title":"Bombay Food Market","adr":"4605 Centre Avenue, Pittsburgh, PA 15213, USA","coords":null,"images":[],"tags":["indian","groceries","ethnic","store"],"_id":"51c0519e02b7cbec73000002"}]);
George L
  • 1,673
  • 2
  • 26
  • 39

1 Answers1

27

try this:

var initData = JSON.parse('<%-JSON.stringify(list)%>');

OR:

var initData = <%-JSON.stringify(list)%>;
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • first one worked perfectly! could you explain why the single quotes makes it work though? – George L Jun 19 '13 at 07:54
  • 1
    @GeorgeL `JSON.parse` takes STRING as parameter and look at your output, you are passing array in `JSON.parse`. single quotes does this: `JSON.parse('[{ "title": "..." }]')` instead of this: `JSON.parse([{ "title": "..." }])` – karaxuna Jun 19 '13 at 09:07
  • 1
    why is initData an object instead of a string? we stringified it – OMGPOP Jun 24 '15 at 12:53
  • @OMGPOP I wonder the same and I guess it's related to the `<%-` operator somehow. `<%=` would fail I think. – Vadorequest Aug 09 '15 at 14:06
  • Be careful, this method does _not_ work for arbitrary objects. For example, regexes end up as empty objects. `{ a: /bcd/ }` will output `{ a: {} }`. This is because regexes have serialization issues - http://stackoverflow.com/questions/12075927/serialization-of-regexp. I don't know if other types have this problem. – Alex Ciminian Aug 25 '15 at 23:30
  • this doesn't work if you replace "South Hills" with "South Hill's" – Danny Dulai Jul 31 '16 at 21:05
  • the first one doesn't -- the second one works fine for single quotes. – Danny Dulai Jul 31 '16 at 21:21