1

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],[............
1
  • 2
    run your JSON through an online validator to see where the problem is. Commented Sep 6, 2015 at 14:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.