JSON Basic Program

JSON Object

In the following example, we will access the name from the object (data variable).

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSON Basic Program</h1> <p id="point"></p> <button onclick="myFunction()">Click Me</button> <script> var data = { name: "Mike", age: 36}; function myFunction(){ document.getElementById("point").innerHTML = data.name; } </script> </body> </html>

JSON Array (Improper Representation)

In the following example, we will access the name of the second object in an array (data variable).

Have a close look at the data variable, where keys are not double quoted. Though you can access the variable without any error, it is basically an invalid json.

Note: It is not recommended to use non-double quoted keys in JSON format because it works well inside a <script> tag or in a JavaScript file (.js). But not in a JSON file (.json)

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSON Basic Program</h1> <p id="point"></p> <button onclick="myFunction()">Click Me</button> <script> var data = [ { name: "Mike", age: 36}, { name: "Alex", age: 30} ]; function myFunction(){ document.getElementById("point").innerHTML = data[1].name; } </script> </body> </html>

JSON Array (Proper Representation)

In the following example, we will access the name of the second object in an array (data variable).

Have a close look at the data variable, where keys are double quoted and it is a valid JSON.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSON Basic Program</h1> <p id="point"></p> <button onclick="myFunction()">Click Me</button> <script> var data = [ { "name": "Mike", "age": 36}, { "name": "Alex", "age": 30} ] function myFunction(){ document.getElementById("point").innerHTML = data[1].name; } </script> </body> </html>

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author