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