We help IT Professionals succeed at work.

How to get external JSON data into a Javascript variable

Alan Varga
Alan Varga asked
on
How do I retrieve "livingroom" from a text file into a javascript string variable that can be displayed with alert?  Using my example below, instead of having the value hardcoded, I want to retrieve the data from the .json file, which will be deployed with a different value to each computer in my home network.  (I am trying VERY hard to avoid using ActiveX with Windows Script Host techniques to get Wscript.Network.ComputerName.)

I have looked at numerous articles on JSON, JQuery and RPC and have only gotten myself confused.  This seems like such a simple thing to do...


file: computerid.json
{"computer": {
  "id": "livingroom"
}}

Open in new window



file: foobar.html
<!DOCTYPE html>
<html lang="en">

<head>
  <title>JSON Example</title>
  <script type="text/javascript"
          src="foobar.js"></script>
  <script type="text/javascript"
          src="jquery-1.7.min.js"></script>
</head>
<body onload="showComputerName();">
</body>
</html>

Open in new window



file: foobar.js
function showComputerName () {
var obj = jQuery.parseJSON('{"id":"livingroom"}');
alert(obj.name);
}

Open in new window


Thanks in advance.
Comment
Watch Question

Commented:
Hi,
to get your function to work you should use alert(obj.id);

To get the json from your file your foobar.js should look like this.

 
function showComputerName () {
	jQuery.getJSON('computerid.json', function(obj) {
		alert(obj.computer.id);
	});
}

Open in new window


I hope this is what your are looking for...
Alan VargaAccess Developer

Author

Commented:
That's perfect; thanks!!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.