0

I'm have trouble to understand how to use the data saved in a JSON file and load it in a html page Everything locally: say this the JSON file :

    { 

    "level1":{
        "level1_1":{
            "example": "test",
            "example2":"123123"
        },
        "level1_2":{
            "example": "test",
            "example2":"123123"
        }
    },

    "level2":{
        "level2_1":{
            "example": "test",
            "example2":"123123"
        },
        "level2_2":{
            "example": "test",
            "example2":"123123"
        }
    }

}

And I want to be able to call the data from it, in and HTML file for example :

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>reading json</title>
  <style>

  </style>

</head>
<body>

  <br>
  file value :

  <br>

<script>
function loadJSON(callback) {   

var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
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);
      }
};
xobj.send(null);  
}

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
}
</script>

</body>

I've got the script from this tutorial and still do get it run. So my aim just to see after ** first value** data from the JSON file. any idea how u guys do it ?

2
  • Before <script> tag ends call init();. Before <script> element starts add <div id="displaydata"></div>. After actual_JSON add document.getElementById("displaydata").innerHTML=actual_JSON; Commented Jul 25, 2019 at 11:50
  • @fiveelements thanks for replying , can u tell how can use the call in html file ? Commented Jul 25, 2019 at 12:06

3 Answers 3

2

Here is a more elaborate answer.

First, let's parse the JSON into an object.

var actual_JSON = JSON.parse(response);

Second, transform the JSON object into a readable string.

var json_string = JSON.stringify(actual_JSON, undefined, 2);

Then, use the querySelector() function to select a DOM element. Note that #output means I want to select an ID attribute named output.

var output = document.querySelector("#output");

Then, I am adding by the JSON string to the DOM with the DOM innerHTML property. It will be added right after "file value".

output.innerHTML += json_string;
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>reading json</title>
  <style>

  </style>

</head>
<body>

  <br>
  <div id="output">file value : </div>
  <br>

<script>

// Starts.
init();

function loadJSON(callback) {   
  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
  xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
  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);
          // init(xobj.responseText)
        }
  };
  xobj.send(null);  
}

function init() {
  loadJSON(function(response) {

    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);

    // Transforms the JSON object into a readable string.
    var json_string = JSON.stringify(actual_JSON, undefined, 2);

    // Select <br> tag.
    var output = document.querySelector("#output");

    // Adds it to the DOM.
    output.innerHTML += json_string;
  });
}

</script>
</body>
Sign up to request clarification or add additional context in comments.

8 Comments

thanks for replying but can u tell how should I call a specific element in html file file
I modified my answer and it is much more complete. I hope it helped you.
I've copied ur answer but still can't any resut ?
It works great for me. Make sure your config.json file is in the same directory as your html file.
index.html:33 Access to XMLHttpRequest at 'file:///C:/Users/Engine/Documents/json/config.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, https.
|
1

You have to add some id attribute in html, then select based on that id and loop the json data and insert like this

<!doctype html>

    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>reading json</title>
      <style>

      </style>

    </head>
    <body>

    <div id="json_result"></div>
<script>
function loadJSON(callback) {   

var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
xobj.open('GET', 'config.json', true); // Replace 'my_data' with the path to your file
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);
      }
};
xobj.send(null);  
}

function init() {

 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response); 

    for (var key in actual_JSON) {
        var innerkey = actual_JSON[key];
        for (var inner in innerkey) {
             document.getElementById('json_result').innerHTML += 'Example: '+innerkey[inner]['example']+'<br>';
             document.getElementById('json_result').innerHTML += 'Example2: '+innerkey[inner]['example2']+'<br>';
        }   
    }   
 }); 
}
init();
</script>

</body>

4 Comments

thanks for reply but your solution seems not to work for me ? here's what I get : index.html:33 Access to XMLHttpRequest at 'file:///C:/Users/Engine/Documents/json/config.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, https
@Engine you can check by replacing the config.json with the absolute path of that file. maybe you can try this json-generator.com/api/json/get/bZKGxFnZDS?indent=2 , i have added you json file data and generated the link
@Maher even after setting up the path i get the same error :/
1

This stack overflow question will guide you well

1 Comment

I found your answer in the question that was asked here. Do not concentrate on the reply but on the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.