Ví dụ 1:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Object in JavaScript</h2>
<div id="demo"></div>
<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj= JSON.parse(text);
document.getElementById("demo").innerHTML= obj.name + "<br>" + obj.street+ "<br>" + obj.phone;
</script>
</body>
</html>
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj= JSON.parse(text);
<script>
document.getElementById("demo").innerHTML=
obj.employees[1].firstName +" "+ obj.employees[1].lastName;
</script>
var obj= eval ("(" + text + ")");
Ví dụ 2:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<h2>JSON Object in JS</h2>
<div id="demo"></div><script>
vartext = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';
varobj= JSON.parse(text);
varst= "";
for (i= 0; i< obj.employees.length; i++) {
st=st+ obj.employees[i].firstName+ " "
+ obj.employees[i].lastName+ "<br>";
}
document.getElementById("demo").innerHTML= st;
</script>
</body>
</html>
» Tin mới nhất:
» Các tin khác: