We help IT Professionals succeed at work.

How to get external JSON data into a Javascript variable

Alan Varga
Alan Varga asked
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">

  <title>JSON Example</title>
  <script type="text/javascript"
  <script type="text/javascript"
<body onload="showComputerName();">

Open in new window

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

Open in new window

Thanks in advance.
Watch Question

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) {

Open in new window

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


That's perfect; thanks!!

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