关闭

JSON基本语法

73人阅读 评论(0) 收藏 举报
分类:

JSON: JavaScript Object Notation(JavaScript 对象表示法)

JSON 数据的书写格式是:名称/值对

"firstName" : "John"

JSON 对象
{ "firstName":"John" , "lastName":"Doe" }

JSON数组
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName":"Jones" }
]
}

JSON赋值及调用
<script>
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" }, 
{ "firstName" : "Anna" , "lastName" : "Smith" }, 
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];
employees[1].firstName="Jonatan";
document.getElementById("fname").innerHTML=employees[0].firstName;
</script>


把 JSON 文本转换为 JavaScript 对象

<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br> 
Last Name: <span id="lname"></span><br> 
</p> 
<script>
var txt = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';//包含 JSON 语法的 JavaScript 字符串

obj = JSON.parse(txt);//解析 JSON 文本,然后生成 JavaScript 对象
document.getElementById("fname").innerHTML=obj.employees[0].firstName 
document.getElementById("lname").innerHTML=obj.employees[1].lastName 
</script>
</body>
</html>



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3748次
    • 积分:291
    • 等级:
    • 排名:千里之外
    • 原创:27篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类