访问嵌套的 JSON 对象

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JSON 对象</h1>
  6.  
  7. <p>如何访问嵌套的 JSON 对象。</p>
  8.  
  9. <p id="demo"></p>
  10.  
  11. <script>
  12. var myObj = {
  13. "name":"Bill Gates",
  14. "age":62,
  15. "cars": {
  16. "car1":"Porsche",
  17. "car2":"BMW",
  18. "car3":"Volvo"
  19. }
  20. }
  21. document.getElementById("demo").innerHTML += myObj.cars.car2 + "<br>";
  22. //or:
  23. document.getElementById("demo").innerHTML += myObj.cars["car2"];
  24. </script>
  25.  
  26. </body>
  27. </html>