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?