[javascript] Trying to load local JSON file to show data in a html page using JQuery

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

This question is related to javascript jquery html json

The answer is


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"
    }]
  }
}

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.


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.


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 ) );
 }); 

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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?