1

I am new to JavaScript. My JavaScript (script.js) reads from a JSON file as shown below. The script reads without using JQuery. I followed THIS site for reference.

function readJSON() {
  var LatLongData = JSON.parse(data);
  var LatLng1 = new google.maps.LatLng(LatLongData[0]);
}

The JSON file (data.json), stored in the same location as the JavaScript is as below:

{ "data": 
[
    {"latitude" : "40.10246648", "longitude" : "-83.14877599"}
]
} 

The html file is as shown below:

<script type="text/javascript" src="data.json"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKey&sensor=true"></script>
<body onload="readJSON()">
  <div id="map-canvas"/>
</body>

I get 2 errors (both in chrome as well as Firebug) on the JSON file format. However, I verified online (http://jsonlint.com/) that the JSON file is of the right format. The errors I get are:

SyntaxError: missing ; before statement { "data":

ReferenceError: data is not defined  ---> var LatLongData = JSON.parse(data);

What am I doing wrong here?

1
  • 1
    prepend "data=" to your 'json' file and it should work Commented Oct 29, 2013 at 21:04

2 Answers 2

3

You can't read the json like that. First of all you should not include it via <script> tag. You need to get the json via ajax request. I'll suggest to check the jQuery's getJSON method:

$.getJSON( "data.json", function( data ) {
   // now you can read the data
   var LatLongData = data;
   var LatLng1 = new google.maps.LatLng(LatLongData[0]);
});

What you are doing is to include the json as javascript file. That's why you got that error. Second, your readJSON uses data variable which is actually never defined.

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

2 Comments

But I am reading the JSON from a file. Do I still need to use ajax?
Ajax is the way to load files via javascript. It's a http request to the file. You could do the same thing via PHP or some other server-side technology, but this should happen before to show the page.
1

You included this Json

{ "data": 
[
    {"latitude" : "40.10246648", "longitude" : "-83.14877599"}
]
} 

but the code is expecting a variable called data, if you pay attention to the example in the link in their "json" file they are "cheating" , it's not pure JSON as is declaring a global variable, containing a string. That string is the json. So if you go ahead following those practice you should have a "json" file.

with

var data = '[ {"latitude" : "40.10246648", "longitude" : "-83.14877599"}]'

but I suggest you to follow Krasimir's answer.

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.