85

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.

3
  • 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. Commented Aug 22, 2012 at 15:20
  • take a look on the link which also provide the examples also api.jquery.com/jQuery.getJSON Commented Aug 23, 2012 at 6:12
  • i am not able to get the example.. please elaborate it... Commented Aug 23, 2012 at 7:09

5 Answers 5

74
<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!!!

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

6 Comments

what if it's a local json file?
people.json is local json only. give the absolute url of your local json to $.getJSON
I have provided absolute path for people.json but it did not work. ex: file:///path/people.json
just disable the CORS policy and it will work see stackoverflow.com/questions/17711924/…
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...
|
27

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

3 Comments

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.
Should mydata.json locate on the same directory with the html file?
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);}).
21

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

Comments

20

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

3 Comments

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...
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.
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."
9

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.