- JSON 实用资源
- JSON - 快速指南
- JSON - 实用资源
- JSON - 讨论
JSON - 对象
创建简单对象
可以使用 JavaScript 创建 JSON 对象。让我们看看使用 JavaScript 创建 JSON 对象的不同方法 -
- 创建空对象 -
var JSONObj = {};
- 创建新对象 -
var JSONObj = new Object();
使用字符串值创建带有 bookname 属性的对象,使用数值创建 price 属性。通过使用 '.' 运算符来访问属性 -
var JSONObj = { "bookname ":"VB BLACK BOOK", "price":500 };
这是一个 JSON 代码示例,展示如何在 javascript 中创建对象,将以下代码保存为 json_object.htm -
<html>
<head>
<title>Creating Object JSON with JavaScript</title>
<script language = "javascript" >
var JSONObj = { "name" : "tutorialspoint.com", "year" : 2005 };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Website Name = "+JSONObj.name+"</h3>");
document.write("<h3>Year = "+JSONObj.year+"</h3>");
</script>
</head>
<body>
</body>
</html>
现在,让我们尝试使用 IE 或任何其他启用 javaScript 的浏览器打开 JSON 对象。它会产生以下结果 -
创建数组对象
以下示例展示如何在 javascript 中创建数组对象,将以下代码保存为 json_array_object.htm -
<html>
<head>
<title>Creation of array object in javascript using JSON</title>
<script language = "javascript" >
document.writeln("<h2>JSON array object</h2>");
var books = { "Pascal" : [
{ "Name" : "Pascal Made Simple", "price" : 700 },
{ "Name" : "Guide to Pascal", "price" : 400 }],
"Scala" : [
{ "Name" : "Scala for the Impatient", "price" : 1000 },
{ "Name" : "Scala in Depth", "price" : 1300 }]
}
var i = 0
document.writeln("<table border = '2'><tr>");
for(i = 0;i<books.Pascal.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Pascal[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Pascal[i].price +"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
for(i = 0;i<books.Scala.length;i++) {
document.writeln("<td>");
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td><b>Name</b></td><td width = 50>" + books.Scala[i].Name+"</td></tr>");
document.writeln("<tr><td><b>Price</b></td><td width = 50>" + books.Scala[i].price+"</td></tr>");
document.writeln("</table>");
document.writeln("</td>");
}
document.writeln("</tr></table>");
</script>
</head>
<body>
</body>
</html>
现在,让我们尝试使用 IE 或任何其他启用 javaScript 的浏览器打开 JSON 数组对象。它会产生以下结果 -
广告