Google Maps API Tutorial© 2006, 2007, 2008, 2009 Mike Williams |
Translate this page: |
Data in JSON filesAnother format in which your data can be stored is JSON.The Javascript to process JSON data is simpler and more efficient than that required to process XML or plain text files. On the downside: the JSON data format has a more complicated structure, so it's more difficult to create and maintain the data file or to write server-side code that will generate JSON files. If your JSON file comes from a trusted source, then you can simply perform an eval command on the JSON data to convert the JSON text into a Javascript object. Treat JSON files obtained from a third party source with as much care as you would with third-part Javascript files. A JSON file can include calls to any accessible Javascript function. Although JSON files parse very efficiently, their file size tends to be larger than XML, so they end up only being slightly faster than XML. Plain text files take longer to parse, but their file size can be much smaller so they take less time to fetch. In my tests, with Firefox, JSON was 7% faster than XML overall, and plain text files were 2% faster than XML. The timings of my test with IE were so wildly variable that the results were meaningless. Here's an example You can see the JSON file that I used here The code defines a function "process_it()" which processes the retrieved data. The entire data file is passed to process_it() as a single string, which we can then parse with the eval command. This creates a Javascript Object that has the properties specified in the JSON file. Unlike XML, JSON files can contain < and >. There's no problem with MIME types either. The code should work whatever MIME type is served. If your JSON file contains numeric data (e.g. {"lat":43.65654} rather than {"lat":"43.65654"}) then you won't need to use parseFloat() and parseInt() to convert the data. ConstructorsIt is also possible to use calls to constructors and other functions inside a JSON file. This can make the Javascript even simpler without making the JSON file much more complicated.This example uses a JSON file that includes calls to new GLatLng() You can see the JSON file that I used here This might give you a clue about possible security issues with using eval to parse JSON data from an untrusted source. Potential Pitfalls
|