58

Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.

<html>
 <head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        

<script type="text/javascript">
    $(document).ready(function(e) {
    $.getJSON( "priorities.json" , function( result ){
        alert(result.start.count);
    });
});
</script></head>
</html>

I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.

{
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

JSON file name priorities.json and error is

Uncaught Referenceerror priorities is not defined

12
  • Check your HTML markup for unclosed tags somewhere. Is the head missing or you just forgot to copy and paste this part of the page? Sep 5, 2013 at 13:20
  • I will parse but first before parsing only it is giving me error. Sep 5, 2013 at 13:20
  • Chrome will not like this.
    – mccannf
    Sep 5, 2013 at 13:21
  • 1
    You error says that you are trying to use an undefined var/object called priorities that doesn't exist and/or is undefined. That code isn't responsible for the error, I think.
    – Joum
    Sep 5, 2013 at 13:22
  • Joum there is no undefined variable Sep 5, 2013 at 13:23

7 Answers 7

47

You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>

data.js:

var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}
5
  • Do you know of any way to display that from the html script? isnt it just console.log(data)?
    – Jouster500
    Aug 7, 2015 at 15:23
  • Ya the code in data.js is globally available from the HTML document, so using data or data.start.count within a <script> element in your HTML will work. Aug 7, 2015 at 19:58
  • 1
    This is also a JavaScript not a Json-Solution! :( Jul 25, 2017 at 13:50
  • It returns empty file, should I write absolute path for the data.js, which also does not work ? @senornestor
    – alper
    Oct 26, 2018 at 10:43
  • Yeah, for offline data testing this is best! :) I was thinking of it while reading all answers above :p Sep 23, 2019 at 6:31
40

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

8
  • This is a nice little hack
    – DucDigital
    Jun 15, 2014 at 12:43
  • 23
    In this "solution" priorities.json is not a JSON file anymore, but a JavaScript file.
    – trincot
    Dec 20, 2016 at 6:11
  • Do you have html file for this as well where I can try to run? @Khanh TO
    – alper
    Oct 26, 2018 at 10:48
  • @alper, I don't, but you can easily create one
    – Khanh TO
    Oct 27, 2018 at 2:32
  • This is not good, I currently am trying to fix a CSP issue, and just calling a json file a javascript file does nobody no good ) :
    – Derrops
    Jun 21, 2021 at 10:59
27

As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."

http://api.jquery.com/jQuery.getJSON/

So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:

Local file access with javascript

2
  • Actually I managed it with my browser - qtweb.net. and I think it is also feasible in Chrome (for example) if you enable an option when you run it: stackoverflow.com/questions/4819060/… .
    – Joum
    Sep 5, 2013 at 13:28
  • yeah that works with chrome, but I would consider that more of a hack than a final solution..
    – hequ
    Sep 5, 2013 at 13:30
4

app.js

$("button").click( function() {
 $.getJSON( "article.json", function(obj) {
  $.each(obj, function(key, value) {
         $("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
  });
 });
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Tax Calulator</title>
    <script src="jquery-3.2.0.min.js" type="text/javascript"></script>
  </head>
  <body>
    <ul></ul>
    <button>Users</button>
<script type="text/javascript" src="app.js"></script>
  </body>
</html>

article.json

{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}

server.js

var http = require('http');
var fs = require('fs');

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/') {
          response.writeHead(200,{"Content-Type":"text/html"});
          fs.createReadStream("./index.html").pipe(response);
  } else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
  } else if(request.method == 'GET' && request.url == '/app.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./app.js").pipe(response);
  }
  else if(request.method == 'GET' && request.url == '/article.json') {
          response.writeHead(200,{"Content-Type":"text/json"});
          fs.createReadStream("./article.json").pipe(response);
  }
}

http.createServer(onRequest).listen(2341);
console.log("Server is running ....");

Server.js will run a simple node http server in your local to process the data.

Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html

This is my running one https://github.com/surya4/jquery-json.

0
3

The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error. It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.

So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.

-3

I would try to save my object as .txt file and then fetch it like this:

 $.get('yourJsonFileAsString.txt', function(data) {
   console.log( $.parseJSON( data ) );
 }); 
1
  • 1
    This has the exact same problem as getJSON.
    – Moss
    Mar 2, 2017 at 3:10
-3

I have Used Following Methods But non of them worked:

   // 2 Method Failed

        $.get(
            'http://www.corsproxy.com/' +
            'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
            function (response) {
                console.log("> ", response);
                $("#viewer").html(response);
            });
// 3 Method Failed

    var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  console.log( "second complete" );
});

// 4 Method Failed

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   success: function(jsondata){
    console.log(jsondata)
   }
})

// 5 Method Failed


$.ajax({
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   headers: {  'Access-Control-Allow-Origin': 'htt://site allowed to access' },
   dataType: 'jsonp',
   /* etc */
   success: function(jsondata){

   }
})

What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:

// Worked After local Web Server

        $(document).ready(function () {
            $.getJSON('./json/movies-coming-soon.json', function (data) {
              var movie_name = '';
              var movie_year = '';
                $.each(data,function(i,item){
                    console.log(item.title,item.year,item.poster)
                    movie_name += item.title + "  " + item.year + "<br> <br>"

                    $('#movie_name').html(movie_name)


                })

            })

        })

Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.