Click here to Skip to main content
15,867,308 members
Articles / Web Development / HTML
Tip/Trick

How to Open a JSON File in JavaScript for Web

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
21 Oct 2018CPOL 20.3K   5   2
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)


Written By
Software Developer
Argentina Argentina
I'm a Software Developer. I like to share knowledgements and I worked with C, C++, C#, VB, PHP, Java, and more...

Comments and Discussions

 
Questionits amazing Pin
Cafe alam di bandung22-Oct-18 1:06
professionalCafe alam di bandung22-Oct-18 1:06 
AnswerRe: its amazing Pin
Matias Lopez22-Oct-18 3:49
Matias Lopez22-Oct-18 3:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.