Ad

Reading Json "element" In Html Page

- 1 answer

say I have the following config.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"
        }
    }
}

I just want to read , say the value of level2_2.example2 in a html file, looking like the following :

<!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>

Calling the HTML file directly delivers the following error :

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, https.

so I have the following nodejs script to run a server:

    var http = require('http');
var fs =require('fs');


var server = http.createServer(function(req,res){
    console.log('request was made : '+req.url);
    res.writeHead(200,{'Content-Type':'text/html'});
    var myReadStream  = fs.createReadStream(__dirname +'/index.html','utf8');
    myReadStream.pipe(res);
});

server.listen('3000','127.0.0.1');

console.log('listening to 3000');

calling the the address delivers than the following error:

 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at (index):40
    at XMLHttpRequest.xobj.onreadystatechange ((index):29)
(anonymous) @ (index):40
xobj.onreadystatechange @ (index):29
XMLHttpRequest.send (async)
loadJSON @ (index):33
init @ (index):37
(anonymous) @ (index):20

So The question here is; what I'm missing or not understand here? and can I call a specific element in the json file ?

Ad

Answer

  function readJsonFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
      if (rawFile.readyState === 4 && rawFile.status == "200") {
        callback(rawFile.responseText);
      }
    }
      rawFile.send(null);
    }

  /* usage */
  readJsonFile("http://localhost/projects-name/my_data.json", function(text){
    var data = JSON.parse(text);
    console.log(data);
  });

NOTE: Use $.get instead of function this if you are getting data from external url.

 $.getJSON("http://localhost/projects-name/my_json", function(text) {

   var PatternData = JSON.parse(JSON.stringify(text));

// 
//readJsonFile("http://localhost/project-name/json/my_data.json", function(text) {

//var PatternData = JSON.parse(text);

📚 Link: https://github.com/gmkhussain/frontend#how-to-get-json-data-from-external-file-in-javascript

Ad
source: stackoverflow.com
Ad