一、对象的语法
JSON 对象被大括号环绕 {},JSON 对象被写成key/value。
- { "name":"John", "age":30, "car":null }
key必须是字符串,并且value必须是一个有效的JSON数据类型(字符串、数字、对象、数组、布尔值或空),Keys 和 values 由冒号分隔,每个key/value对被逗号分隔。
二、访问对象的值
可以使用点(.)访问对象值。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>项目</title>
- </head>
- <body style="background-color: aqua;">
- <p>Access a JSON object using dot notation:</p>
- <p id="demo"></p>
- <script>
- var myObj, x;
- myObj = {
- "name": "John",
- "age": 30,
- "car": null
- };
- x = myObj.name;
- document.getElementById("demo").innerHTML = x;
- </script>
- </body>
- </html>
还可以使用方括号([])访问对象值:
- <script>
- var myObj, x;
- myObj = {
- "name": "John",
- "age": 30,
- "car": null
- };
- x = myObj["name"];
- document.getElementById("demo").innerHTML = x;
- </script>
三、循环一个对象
可以使用for-in循环,遍历一个对象。
- <script>
- var myObj = {
- "name": "John",
- "age": 30,
- "car": null
- };
- for (x in myObj) {
- document.getElementById("demo").innerHTML += x + "<br>";
- }
- </script>
使用括号表示法访问属性值:
- <script>
- var myObj, x;
- myObj = {
- "name": "John",
- "age": 30,
- "car": null
- };
- x = myObj["name"];
- document.getElementById("demo").innerHTML = x;
- </script>
四、嵌套的 JSON 对象
JSON的值可以是另外一个JSON对象。
- myObj = {
- "name":"John",
- "age":30,
- "cars": {
- "car1":"Ford",
- "car2":"BMW",
- "car3":"Fiat"
- }
- }
您可以访问嵌套的JSON对象使用点符号或括号:
- x = myObj.cars.car2;
- //or:
- x = myObj.cars["car2"];
1. 修改值
你可以使用点表示法修改JSON对象的任何值:
- myObj.cars.car2 = "Mercedes";
js完整代码:
- <script>
- var myObj, i, x = "";
- myObj = {
- "name":"John",
- "age":30,
- "cars": {
- "car1":"Ford",
- "car2":"BMW",
- "car3":"Fiat"
- }
- }
- myObj.cars.car2 = "Mercedes";
- for (i in myObj.cars) {
- x += myObj.cars[i] + "<br>";
- }
- document.getElementById("demo").innerHTML = x;
- </script>
你也可以使用方括号来修改一个JSON对象值:
- myObj.cars["car2"] = "Mercedes";
js完整代码:
- <script>
- var myObj, i, x = "";
- myObj = {
- "name":"John",
- "age":30,
- "cars": {
- "car1":"Ford",
- "car2":"BMW",
- "car3":"Fiat"
- }
- }
- myObj.cars["car2"] = "Mercedes";
- for (i in myObj.cars) {
- x += myObj.cars[i] + "<br>";
- }
- document.getElementById("demo").innerHTML = x;
- </script>
2. 删除对象的属性
使用delete关键字从JSON对象删除一个属性:
- delete myObj.cars.car2;
完整代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>项目</title>
- </head>
- <body style="background-color: aqua;">
- <p>How to delete properties of a JSON object.</p>
- <p id="demo"></p>
- <script>
- var myObj, i, x = "";
- myObj = {
- "name": "John",
- "age": 30,
- "cars": {
- "car1": "Ford",
- "car2": "BMW",
- "car3": "Fiat"
- }
- }
- delete myObj.cars.car2; //通过语句删除内容。
- for (i in myObj.cars) {
- x += myObj.cars[i] + "<br>";
- }
- document.getElementById("demo").innerHTML = x;
- </script>
- </body>
- </html>
五、总结
本文基于JavaScript基础,介绍了json 对象中,语法的使用,如何去访问对中的值,如何去循环对象。如何去嵌套JSON 对象。对象中如何去嵌套数组,常见的修改,删除数组,都做了详细的讲解。
通过丰富的案例分析,效果图的展示,能够帮助你更好的理解。