Maybe it is very difficult for you to connect to the Json file and retrieve data, today I want to make it easy for you 🙂 Lets start.
Follow these steps:
- We need a Json file for the source that produces Json data for us. To make a Json file please follow these steps :
- Make a new text file and copy this information to the file
"one": "Singular sensation", "two": "Beady little eyes", "three": "Little birds pitch by my doorstep"
- Change the file extension to the Json
- Now you have Json file that contains data , please copy the file in your project ( I assumed you are working in Visual studio )
- There two types of instructions that you can follow to read a Json file , Today I want to use $.getJSON (This a JQuery function)
<script> $(document).ready(function () { $.getJSON("Data/info.Json.", function (data) { var items = []; $.each(data, function (key, val) { items.push("<li id='" + key + "'>" + val + "</li>"); }); $("<H1>", { "class": "my-new-list", html: items.join("") }).appendTo("body"); }); }) </script>
GetJSON hast two parameters
- Source of JSON , it could be URL or the address of JSON file
- The function that gets data from JSON source
$.getJSON("Data/info.Json.", function (data) {
4. Then we should add data to the array
$.each(data, function (key, val) { items.push("<li id='" + key + "'>" + val + "</li>"); }); </script>
5. And in the last step we should add the HTLM codes that we generated in the previous step to the body tag.
$("<H1>", { "class": "my-new-list", html: items.join("") }).appendTo("body"); });
And do not forget to add JQuery reference to your code , it coule be like this :
<script src="~/Scripts/jquery-ui-1.8.20.js"></script> <script src="~/Scripts/jquery-1.7.1.js"></script>