Reputation: 31
I had to read a json file by javascript during an interview.
The json file is almost like this:
{ apple: {price: 1}, banana: {price: 2} }
I have got some solutions like:
However when I asked the Interviewer, he gave me the hints:
load json file to html using script tag like this:
script type="application/json" src="scripts/data.json"
then read the data in your js file by eval(json)
I was confused: how could I access the data just by loading it as script tags without modifing?
Upvotes: 2
Views: 9200
Reputation: 17710
You may have a bad recollection of the details of the questions.
Obviously, the first part of the question involves Ajax (XmlHttpRequest).
The second part is probably related to JSONP, where you modify the server output so that it looks more like function(<json data here>)
, with the function name being provided by the client to the server (though that's really implementation-specific). JSONP used to be a common pattern a few years back (mostly as a backwards compatibility solution for browsers without XHR support, but also to bypass cross-domain limitations). Probably a lot less these days, as it has a few significant security issues. If you want to read more about it: https://en.wikipedia.org/wiki/JSONP
JSONP does not, however, involve the use of eval
, but has the same kind of security issues: anything goes.
Upvotes: 0
Reputation: 410
You can't do it this way:
HTML/Javascript: how to access JSON data loaded in a script tag with src set
Could this be a trick question from the interviewer..?
Use ajax, that is the only proper way to do it in my opinion. Other solutions fall into the hack-category.
Also, as mentioned by Franco, don't use eval(), unless you have to support very old browsers and don't care about security. Use JSON.parse() instead. It's even supported by IE8. Calling eval evaluates/executes its argument - so this is an attack vector for someone trying to inject malicious code into your site.
Upvotes: 3
Reputation: 2329
You will need to get the json file (this suppose you want to get it by a button click):
$(document).ready(function(){
$("button").click(function(){
$.getJSON("your-json.js", function(result){
$.each(result, function(i, val){
//you can do something with your returned data.
});
});
});
});
NOTE: don't use eval(), this is a bad practice.
Upvotes: -1