Sarvavyapi
Sarvavyapi

Reputation: 850

Error while reading from local JSON file in JavaScript

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?

Upvotes: 1

Views: 6868

Answers (2)

alfonsodev
alfonsodev

Reputation: 2754

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.

Upvotes: 1

Krasimir
Krasimir

Reputation: 13529

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.

Upvotes: 3

Related Questions