Avatar of Wayne Barron
Wayne Barron
Flag for United States of America asked on

Parse JSON from linked file. (Working example of hard coded XML)

Hello, All.

I found this script which is rather promising for what I am trying to do.
It works great with the hard-coded XML script.
However, I need to parse the file itself from a link.
Could someone please assist in making this work with a linked file?

Thank You.

Contents of the example file.
{"icestats":{"admin":"admin","host":"192.168.2.203","location":"Radio","server_id":"Icecast 2.4.4","server_start":"Mon, 24 May 2021 16:54:10 +0000","server_start_iso8601":"2021-05-24T16:54:10+0000","source":{"audio_info":"channels=2;samplerate=44100;bitrate=256","channels":2,"genre":"various","listener_peak":3,"listeners":2,"listenurl":"http://192.168.2.203:8000/RadioOne","samplerate":44100,"server_description":"Unspecified description","server_name":"RadioOne","server_type":"audio/mpeg","stream_start":"Mon, 24 May 2021 21:59:34 +0000","stream_start_iso8601":"2021-05-24T21:59:34+0000","title":"KISS - Hide Your Heart","dummy":null}}}

Open in new window

Example of the linked file.
http://192.168.2.203:8000/status-json.xsl

Open in new window


Full script (This will run and show your the XML tree without any modifications to the file)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Parse Nested JSON Data in JavaScript</title>
</head>
<body>
    <script>
    /* Storing multi-line JSON string in a JS variable
    using the new ES6 template literals */
   var json = '{"icestats":{"admin":"admin","host":"192.168.2.203","location":"Radio","server_id":"Icecast 2.4.4","server_start":"Mon, 24 May 2021 16:54:10 +0000","server_start_iso8601":"2021-05-24T16:54:10+0000","source":{"audio_info":"channels=2;samplerate=44100;bitrate=256","channels":2,"genre":"various","listener_peak":3,"listeners":2,"listenurl":"http://192.168.2.203:8000/RadioOne","samplerate":44100,"server_description":"Unspecified description","server_name":"RadioOne","server_type":"audio/mpeg","stream_start":"Mon, 24 May 2021 21:59:34 +0000","stream_start_iso8601":"2021-05-24T21:59:34+0000","title":"KISS - Hide Your Heart","dummy":null}}}';
   
   
   // This is the link to the file, the contents of the file is what is above.
   //var json = "http://192.168.2.203:8000/status-json.xsl";
    
    // Converting JSON object to JS object
    var obj = JSON.parse(json);
    
    // Define recursive function to print nested values
    function printValues(obj) {
        for(var k in obj) {
            if(obj[k] instanceof Object) {
                printValues(obj[k]);
            } else {
                document.write(obj[k] + "<br>");
            };
        }
    };
    
    printValues(obj);
    
    document.write("<hr>");
    document.write(obj["icestats"]["source"]["title"]); 
    </script>
</body>
</html>

Open in new window

JavaScriptXMLJSON

Avatar of undefined
Last Comment
Zvonko

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Zvonko

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Zvonko

and here the not recommanded version without jQuery:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Zvonko &#42;</title>
</head>
<body>
    <script>
   // your JSON string
   var yourJson = '{"icestats":{"admin":"admin","host":"192.168.2.203","location":"Radio","server_id":"Icecast 2.4.4","server_start":"Mon, 24 May 2021 16:54:10 +0000","server_start_iso8601":"2021-05-24T16:54:10+0000","source":{"audio_info":"channels=2;samplerate=44100;bitrate=256","channels":2,"genre":"various","listener_peak":3,"listeners":2,"listenurl":"http://192.168.2.203:8000/RadioOne","samplerate":44100,"server_description":"Unspecified description","server_name":"RadioOne","server_type":"audio/mpeg","stream_start":"Mon, 24 May 2021 21:59:34 +0000","stream_start_iso8601":"2021-05-24T21:59:34+0000","title":"KISS - Hide Your Heart","dummy":null}}}';
   
   
   // fetch the JSON data from your URL:   
   var xfetch = new XMLHttpRequest();   
   xfetch.open("GET", "http://localhost:8000/status-json.xsl", false);
   xfetch.send();
   
   console.log(xfetch.response);
   showData(xfetch.response);
   

   function showData(data){
      // Converting JSON string to JS object
      var jsobj = JSON.parse(data);
      printValues(jsobj);
      console.log("_______________________________");
      if(jsobj["icestats"] && jsobj["icestats"]["source"]){
         console.log(jsobj["icestats"]["source"]["title"]);
      }
      
      // Converting your JSON string from top to JS object
      var jsonobj = JSON.parse(yourJson);
      printValues(jsonobj);
      console.log("_______________________________");
      if(jsonobj["icestats"] && jsobj["icestats"]["source"]){
         console.log(jsonobj["icestats"]["source"]["title"]);
      }
    }
   
    // Define recursive function to print nested values
    function printValues(obj) {
        for(var k in obj) {
            if(obj[k] instanceof Object) {
                printValues(obj[k]);
            } else {
                console.log(k + ": " + obj[k]);
            };
        }
    };
    </script>
</body>
</html>

Open in new window


Zvonko

and here the fetch method:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Zvonko &#42;</title>
</head>
<body>
<ul id="output"></ul>
<script>   
function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('output');
const url = "http://localhost:8000/status-json.xsl";

fetch(url)
.then((resp) => resp.json())
.then(function(data) {
  console.log(data);
  let icestats = data.icestats;
  for (const [key, value] of Object.entries(icestats)) {
    let li = createNode('li');
    let span = createNode('span');
    span.innerHTML = `${key}: ${value}`;
    append(li, span);
    append(ul, li);
  }
})
.catch(function(error) {
  console.log(error);
});
</script>
</body>
</html>

Open in new window



Your help has saved me hundreds of hours of internet surfing.
fblack61