0

I have a file data3.json:

{
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"
}

I want to read this file with JavaScript (and JQuery) and store the values into an object.

I have the HTML file (same directory):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JSON Sample</title>
</head>
<body>
<p>
Name: <span id="jname"></span><br />
Age: <span id="jage"></span><br />
Address: <span id="jstreet"></span><br />
Phone: <span id="jphone"></span><br />
</p>

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
var JSONObject = {};

function add(key, value)  {
    JSONObject[key] = value;
}

add("name", "John Johnson");

$.getJSON('data3.json', function(data) {
        $.each( data, function( key, val ) {
            console.log(JSONObject);
            console.log(key + ": " + val);
            JSONObject[key] = val;
        });
});
$("#jname")[0].innerHTML    = JSONObject.name;
$("#jage")[0].innerHTML = JSONObject.age;
$("#jstreet")[0].innerHTML  = JSONObject.street;
$("#jphone")[0].innerHTML   = JSONObject.phone;
</script>

</body>
</html>

In Browser I get:

Name: John Johnson
Age: undefined
Address: undefined
Phone: undefined

In console I get:

street: Oslo West 555
Object { street="Oslo West 555"}
age: 33
Object { street="Oslo West 555", age=33}
phone: 555 1234567
Object { street="Oslo West 555", age=33, phone="555 1234567"}

I have tested adding value inside the function with the function add(...), which works fine. Inside of $.getJSON the variable became local...

How can force $.getJSON to add the data to my variable JSONObject?

Andreas L.
  • 2,805
  • 23
  • 23
  • 1
    `$.getJSON` is async. You should read: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – A. Wolff Jun 06 '14 at 12:48

1 Answers1

1
$.getJSON('data3.json', function(data) {

     JSONObject = data;

     $("#jname").html(JSONObject.name);
     $("#jage").html(JSONObject.age);
     $("#jstreet").html(JSONObject.street);
     $("#jphone").html(JSONObject.phone); 

});
Sark
  • 4,458
  • 5
  • 26
  • 25
  • Thank for reply. Your solution works to get the data into HTML, but I want to keep the data also in the variable JSONObject. – Andreas L. Jun 06 '14 at 13:18
  • Not it is not, if i try: $.getJSON('data3.json', function(data) { JSONObject = data; }); $("#jage")[0].innerHTML = JSONObject.age; $("#jstreet")[0].innerHTML = JSONObject.street; $("#jphone")[0].innerHTML = JSONObject.phone; – Andreas L. Jun 06 '14 at 13:28
  • no need of using array index $("#jage")[0]'. a span element with 'jage' id can be accessed like $("#jage") and value can be changed through $("#jage").html(''); – Sark Jun 06 '14 at 13:35
  • if you run, alert(JSON.stringify(JSONObject)); you can see those values. – Sark Jun 06 '14 at 13:38
  • I understand what you are saying, but try to use the content after });, outside of $.getJSON. – Andreas L. Jun 06 '14 at 14:07