Link to home
Start Free TrialLog in
Avatar of Alan Varga
Alan VargaFlag for United States of America

asked on

How to get external JSON data into a Javascript variable

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.
ASKER CERTIFIED SOLUTION
Avatar of ventiro
ventiro

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alan Varga

ASKER

That's perfect; thanks!!