71

I have json file mydata.json, and in this file is some json-encoded data.

I want obtain this data in file index.html and process this data in JavaScript. But a don't know how to connect.json file in .html file?

Tell me please. Here is my json file:

{
    "items": [
        {
            "movieID": "65086",
            "title": "The Woman in Black",
            "poster": "/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"
        },
        {
            "movieID": "76726",
            "title": "Chronicle",
            "poster": "/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"
        }
    ]
} 

Thinking that I am getting json file from server, how to use that file in my html, so that I can display the data in tables in html page. I am using JavaScript to parse the json file. I am new to this field. Help out please.

Tiago Sippert
  • 1,324
  • 7
  • 24
  • 33
saikiran
  • 2,247
  • 5
  • 27
  • 42
  • 2
    Hi, you might consider adding more detail to your question. Are you using any JavaScript frameworks? (ie: jQuery) What have you tried already? What is the desired end result? A good question with a clear goal will help get good answers and examples from the community! Use the 'edit' link below your question to revise it. – BenSwayne Aug 22 '12 at 15:20
  • take a look on the link which also provide the examples also http://api.jquery.com/jQuery.getJSON/ – jogesh_pi Aug 23 '12 at 06:12
  • i am not able to get the example.. please elaborate it... – saikiran Aug 23 '12 at 07:09

5 Answers5

71
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

<script>

    $(function() {


   var people = [];

   $.getJSON('people.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
           "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>

<div class="wrapper">
<div class="profile">
   <table id= "userdata" border="2">
  <thead>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email Address</th>
            <th>City</th>
        </thead>
      <tbody>

       </tbody>
   </table>

</div>
</div>

</body>
</html>

My JSON file:

{
   "person": [
       {
           "firstName": "Clark",
           "lastName": "Kent",
           "job": "Reporter",
           "roll": 20
       },
       {
           "firstName": "Bruce",
           "lastName": "Wayne",
           "job": "Playboy",
           "roll": 30
       },
       {
           "firstName": "Peter",
           "lastName": "Parker",
           "job": "Photographer",
           "roll": 40
       }
   ]
}

I succeeded in integrating a JSON file to HTML table after working a day on it!!!

trevorp
  • 1,161
  • 1
  • 14
  • 19
saikiran
  • 2,247
  • 5
  • 27
  • 42
  • 4
    what if it's a local json file? – Rohit Tigga Jun 07 '16 at 01:59
  • people.json is local json only. give the absolute url of your local json to $.getJSON – saikiran Jun 07 '16 at 04:43
  • 1
    I have provided absolute path for people.json but it did not work. ex: `file:///path/people.json` – alper Oct 25 '18 at 21:14
  • 1
    just disable the CORS policy and it will work see https://stackoverflow.com/questions/17711924/disable-cross-domain-web-security-in-firefox – Mohit Dec 19 '18 at 13:39
  • CORS origin policy is a real problem in my case. I need my customers to see the page locally, so I can't tell them to disable their CORS origin... – TOPKAT Apr 21 '20 at 14:45
  • Ive followed thoroughly, it is working. When published over HTTP its all nice and dandy, yet when i publish over HTTPS Im only getting the Table header and thats it, as if part of the content is blocked, any ideas ?? TY ! – Ilya Gurenko May 05 '20 at 16:39
28

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});
Nicolas Brown
  • 1,546
  • 1
  • 10
  • 17
  • 2
    how to link up the jquery in my html file.. please help me ! i want full code. i want to display my data in a table in my html page. give a sample code. so i can understand easily. thanking you in anticipation. – saikiran Aug 23 '12 at 07:05
  • 1
    Should `mydata.json` locate on the same directory with the `html` file? – alper Oct 25 '18 at 21:17
  • 1
    It's useful to add an error handler otherwise `getJSON` will fail silently and you'll struggle to understand why it doesn't work : add `.fail(function(jqxhr, status, error) { alert(status + ", " + error);})`. – Skippy le Grand Gourou Jan 17 '20 at 11:00
18

You can easily do this without using Jquery or AJAX like below. Here, I used fetch API (Built-in).

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
</head>
<body>
<div id="myData"></div>
<script type="text/javascript">
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });

    function appendData(data) {
        let mainContainer = document.getElementById("myData");
        for (let i = 0; i < data.length; i++) {
            let div = document.createElement("div");
            div.innerHTML = 'Name: ' + data[i].firstName + ' ' + data[i].lastName;
            mainContainer.appendChild(div);
        }
    }
</script>
</body>
</html>

data.json

[
  {
    "id": "1",
    "firstName": "John",
    "lastName": "Doe"
  },
  {
    "id": "2",
    "firstName": "Mary",
    "lastName": "Peterson"
  },
  {
    "id": "3",
    "firstName": "George",
    "lastName": "Hansen"
  }
]
Sathnindu Kottage
  • 1,083
  • 6
  • 17
14

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Quantum7
  • 3,165
  • 3
  • 34
  • 45
Javed
  • 1,613
  • 17
  • 16
  • 56
    that abc.json is not a valid json file, its actual javascript, so here you are just calling a javascript file "abc.json" and loading it... – Israel Cruz Oct 18 '17 at 04:44
  • 6
    If you want to load an array into a JavaScript variable from this "JSON" you can just remove the outside single quotes. In this case `data` would be an array containing objects with a `name` property. No need for `JSON.parse()` in this case. – Grant Davis Feb 20 '18 at 19:42
  • This is what exactly I was looking for. It helps in avoiding CORS error in case someone want to read a file from local html page (without having WebServer). Something like: "file:///C:/dir/jsoncors.html. Othewise browser gives following error: "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https." – user3731930 Mar 12 '20 at 17:44
5

Here's how to do it in plain JavaScript.

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Test Page</title>
    </head>
    <body>
        <h2>Movie List</h2>
        <table id = "tb1" border = "1">
            <tr>
                <th>movieID</th>
                <th>title</th>
                <th>poster</th>
            </tr>
        </table>
        <script>
            fetch("mydata.json")
                .then(response => response.json())
                .then(data => {
                    for (var i = 0; i<data.items.length; i++){
                        let vmovieID = data.items[i].movieID;
                        let vtitle = data.items[i].title;
                        let vposter = data.items[i].poster;
                            document.querySelector("#tb1").innerHTML += `
                                <tr>
                                    <td>${vmovieID}</td>
                                    <td>${vtitle}</td>
                                    <td>${vposter}</td>
                                </tr>`;
                    }
                })
        </script>
    </body>
</html>

mydata.json

{
    "items": [
        {
            "movieID": "65086",
            "title": "The Woman in Black",
            "poster": "/kArMj2qsOnpxBCpSa3RQ0XemUiX.jpg"
        },
        {
            "movieID": "76726",
            "title": "Chronicle",
            "poster": "/853mMoSc5d6CH8uAV9Yq0iHfjor.jpg"
        }
    ]
}
Sahan0710
  • 94
  • 1
  • 4