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 ?

Rob
  • 14,746
  • 28
  • 47
  • 65
Engine
  • 5,360
  • 18
  • 84
  • 162
  • Before ` – fiveelements Jul 25 '19 at 11:50
  • @fiveelements thanks for replying , can u tell how can use the call in html file ? – Engine Jul 25 '19 at 12:06

3 Answers3

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>
Alexis Philip
  • 517
  • 2
  • 5
  • 23
  • thanks for replying but can u tell how should I call a specific element in html file file – Engine Jul 25 '19 at 12:05
  • I modified my answer and it is much more complete. I hope it helped you. – Alexis Philip Jul 25 '19 at 13:16
  • I've copied ur answer but still can't any resut ? – Engine Jul 25 '19 at 13:28
  • It works great for me. Make sure your `config.json` file is in the same directory as your `html` file. – Alexis Philip Jul 25 '19 at 13:31
  • 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 Jul 25 '19 at 13:52
  • this what I get – Engine Jul 25 '19 at 13:53
  • I think this the issue : https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local/21608670 – Engine Jul 26 '19 at 07:27
  • @Engine I am not an expert in `XMLHttpRequest` but I know it is possible to encounter issues like the one you have. Try the code on a web server and it should work. – Alexis Philip Jul 26 '19 at 08:49
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>
Mehar
  • 2,158
  • 3
  • 23
  • 46
  • 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 Jul 25 '19 at 14:02
  • @Engine you can check by replacing the config.json with the absolute path of that file. maybe you can try this http://www.json-generator.com/api/json/get/bZKGxFnZDS?indent=2 , i have added you json file data and generated the link – Mehar Jul 26 '19 at 05:30
  • @Maher even after setting up the path i get the same error :/ – Engine Jul 26 '19 at 07:07
  • 1
    I think this the issue : https://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local/21608670 – Engine Jul 26 '19 at 07:27
1

This stack overflow question will guide you well

Odwori
  • 1,460
  • 13
  • 14
  • I found your answer in the question that was asked here. Do not concentrate on the reply but on the question. – Odwori Jul 25 '19 at 12:40