Ways to Add JSON


  • turned_in_notThis can be done in two ways
    • External JSON
    • Internal JSON

External JSON

  • Declare JSON code in a separate .json file and then access that file in your HTML document
  • Below we are using AJAX to access json external file
Example:
  • turned_in_notExternal JSON
    <!DOCTYPE html>
    <html>
    <head><title>HTML External JSON Example</title></head>
    <body>
    <p>Hi, My name is <span id="show"></span></p>
    <script>
     var xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       var myObj = JSON.parse(this.responseText);
       document.getElementById("show").innerHTML = myObj.name;
     }
    };
    xmlhttp.open("GET", "jsoncode.json", true);
    xmlhttp.send(); 
    </script>
    </body>
    </html>
    "jsoncode.json" file
    { "name":"Riya","age":23 }
    OUTPUT

    Hi, My name is

Internal JSON

  • Declare JSON code inside a variable as a string
Example:
  • label_outlineInside javaScript
    var jsonCode='{ "name":"Rahul", "age":23, "education":"B.Tech" }';
  • label_outlineInside php
    $jsonCode='{ "name":"Rahul", "age":23, "education":"B.Tech" }';
  • How to access the values, we will let you know in coming section

  • Parse
❮ Prev Syntax
receipt