Black John
Black John

Reputation: 31

Try to load json file directly into HTML and read its contents by javascript

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:

  1. read it by the help of ajax method
  2. modify json file like "var json= { apple: {price: 1}, banana: {price: 2} }" and load it into HTML just like a javascript file, so I can read it as a global variable

However when I asked the Interviewer, he gave me the hints:

  1. load json file to html using script tag like this:

    script type="application/json" src="scripts/data.json"

  2. 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

Answers (3)

jcaron
jcaron

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

Henrik Nielsen
Henrik Nielsen

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

Franco
Franco

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

Related Questions