Introduction
Hello! This post will show you how to open and show JSON files in JavaScript for Web.
I know that there're too much information on the Internet, but some code didn't work for me. For this reason, I posted this article to show "How to open a JSON file in JavaScript for Web".
Background
I learnt something of Ajax and XMLHttpRequest
in this post:
Code
Now we can train with a local JSON variable:
<!DOCTYPE html>
<html>
<body>
<h2>Create JSON string from a JavaScript array.</h2>
<p id="demo"></p>
<script>
var arr = [
{
"name": "John",
"surname": "Doe",
"age": 31,
"city": "New York"
},
{
"name": "Jane",
"surname": "Doe",
"age": 26,
"city": "Seattle"
},
{
"name": "Dave",
"surname": "Smith",
"age": 45,
"city": "LA"
},
{
"name": "Alessia",
"surname": "Smith",
"age": 41,
"city": "Texas"
}
];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Well, we can start coding something! Let's write a JSON file (I saved it as Persons.json):
[{'name':'John','surname':'Doe','age':31,'city':'New York'},
{'name':'Jane','surname':'Doe','age':26,'city':'Seattle'},
{'name':'Dave','surname':'Smith','age':45,'city':'LA'},
{'name':'Alessia','surname':'Smith','age':41,'city':'Texas'}]
Then we can write a WebPage
with our JavaScript! Like this:
<!DOCTYPE html>
<html>
<body>
<h2>Create a JavaScript array from JSON string.</h2>
<p id="demo"></p>
<script>
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
} else {
callback("[{\"Nothing\"}]");
}
};
xobj.open('GET', 'Persons.json', true);
xobj.send(null);
};
loadJSON(function(response) {
document.getElementById("demo").innerHTML = JSON.stringify(response);
});
</script>
</body>
</html>
That's It!
It's a very quick scripting WebPage where we can handle local JSON files. I hope that it'll be useful for you!
If you need more, you can search something like WebServices, etc.
If you liked the post, spare some time to give me a vote/comment, it would be appreciated.