Reputation: 41
I tried to pass a Json object to JavaScript function but it gave me an error, Uncaught SyntaxError: Unexpected identifier.
My Json file (bikedata) bike.json (I converted it to app.locals.bikedata= require('./bike.json'); )
[
{
"id":1,
"Station":2,
"MainStreet":"Queen St",
"CrossStreet":"Eagle St",
"Suburb":"City",
"Racks (Approx)":23,
"Bikes @ 2 racks/bike":12,
"Latitude":-27.466369,
"Longitude":153.029597
},
{
"id":2,
"Station":3,
"MainStreet":"Elizabeth St",
"CrossStreet":"Creek St",
"Suburb":"City",
"Racks (Approx)":21,
"Bikes @ 2 racks/bike":11,
"Latitude":-27.467925,
"Longitude":153.029126
},..............
my code in .ejs
<a class="page-scroll" href="javascript:void(0)" onclick="matchBike(<%= bikedata %>)">City Bike</a>
my error Uncaught SyntaxError: Unexpected identifier
<a class="page-scroll" href="javascript:void(0)" onclick="matchBike([object Object],[object Object],[............
Upvotes: 1
Views: 878
Reputation: 700850
You have already parsed the JSON into an array of objects, so when you write it out it will be the string representation of the objects.
Turn the array of objects into JSON so that you can use it as JavaScript code in the call:
<%= JSON.stringify(bikedata) %>
Alternatively make sure that you read the JSON file as text, so that you get a string with the JSON code, not an array of objects.
Upvotes: 2