2

I have included my json file like this

<script type="text/javascript" src="slideshows/1/myfile.json"></script>

And I wonder how I can now create a js object from this file?

If the json was defined inline, or defined in a .js-file it would already have a variable connected to it, but how does it work now that it is in a separate json file?

2
  • 2
    I would use jQuery - getJSON( url, [data], [callback] ) to call json file and instantiate in callback method Commented May 20, 2014 at 9:02
  • JSON is application/json not application/javascript. It isn't a programming language. Commented May 20, 2014 at 9:07

2 Answers 2

3

A JSON file is not a script. It is data.

You need to use a data access method, such as jQuery's $.getJSON() to get it.

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

2 Comments

And loading it over such an ajax call will still utilise the cached version of myfile.json as long as it is included in the cache manifest am I right?
I'm not an expert on caching rules, but that sounds about right.
1

Using script tags to import JSON in the page has only on useful use case, which is a way to prevent Cross-origin security issue from happening. We use it as JSONP in JavaScript by sending a callback attribute on the query-string:

<script type="text/javascript"">
    window.getMyJSON = function(json){

    };
</script>

<script type="text/javascript"
        src="http://someotherdomain/slideshows/1/myfile.json?callback=getMyJSON">
</script>

BUT it seems here the JSON file is located just on the current domain, so as @Scimonster has pointed out you can simply achieve it using $.getJSON().

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.