Objects, Arrays: JSON Using jQuery

Video tutorial illustrates the basics of JSON: Create Object, Arrays, Access Elements, Modify/Update the value etc.

JSON full form: JavaScript Object Notation.

JSON is a lightweight data-interchange format.
It’s easy for humans to read and write.
It’s easy for machines to parse and generate.
So it’s more efficient at transferring data than XML.

HTML code
index.html


JSON and jQuery!


    We have a simple HTML structure, with a unorder list.
    We’ll fill the list items from the JSON data using jQuery.

    JSON and jQuery
    my_script.js

    $(document).ready( function() {
    
     var v1 = { "name": "Satish", "age": 25, "company": "Technotip IT Solutions" };
     var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
     
     var obj = { "obj1": v1, "obj2": v2 };
     
     var v3 = { "companies": [ "Microsoft", "Apple", "Google", "Oracle" ] };
     
      $("ul").append("
  • "+obj["obj1"]["name"]+"
  • "); $("ul").append("
  • "+v3.companies[0]+"
  • "); });

    Object
    An object is a set of name/value pairs. An object begins with { and ends with }. Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

    Array
    An array is an ordered collection of values. An array begins with [ and ends with ]. Values are separated by , (comma).
    Values in JSON can be string, number, array, objects, Boolean values or even null.

    Fetch JSon Data From Object:
    Object_name.Key;

    Fetch JSon Data From Array:
    Object_name.array_name[index_number];

    Update JSON Data:

    JSON and jQuery
    my_script.js

     var v2 = { "name": "Kiran", "age": 28, "company": "Oracle" };
      $("ul").append("
  • "+v2.company+"
  • "); v2.company = "Apple"; $("ul").append("
  • "+v2.company+"
  • ");

    Would output
    Oracle
    Apple

    Similarly, we could change the value of any key of an object or an array element.

    Video Tutorial: Objects, Arrays: JSON Using jQuery



    YouTube Link: https://www.youtube.com/watch?v=MK39DQabaW8 [Watch the Video In Full Screen.]



    We could nest objects inside objects or arrays inside objects or objects inside an array etc, upto any level of complexities.
    This is advantages for web applications like building menus with nested items, which are fetched from database.

    Since, writing and fetching and parsing of JSON data is easy, most developers have stared using JSON over XML.

    View Comments

    • Thanks you Sir... you save my lot of time.
      your method also works nicely to .php file instead of .json file.