We help IT Professionals succeed at work.
Get Started

How to get external JSON data into a Javascript variable

Alan Varga
Alan Varga asked
on
391 Views
Last Modified: 2012-06-21
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:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE