Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

How to Open a JSON File in JavaScript for Web

5.00/5 (2 votes)
21 Oct 2018CPOL 20.8K  
How to open a JSON file in JavaScript for Web

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:

ASP.NET
<!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):

JavaScript
[{'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:

ASP.NET
<!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") {
                                // Required use of an anonymous callback as .open will NOT return 
                                // a value but simply returns undefined in asynchronous mode
                                callback(xobj.responseText);
                            } else {
                                callback("[{\"Nothing\"}]");
                            }
                        };

                    xobj.open('GET', 'Persons.json', true);
                    // Maybe you require use of an unknown origin.
                    /*xobj.setRequestHeader("Access-Control-Allow-Origin","*");*/
                    xobj.send(null);  
                };
            
            loadJSON(function(response) {
                    // Parse JSON string into object
                    //document.getElementById("demo").innerHTML = JSON.parse(response);
                    // Parse JSON array string into object
                    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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)