Click here to Skip to main content
Click here to Skip to main content
Technical Blog

JSON Object Code Example

, 13 Jun 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
An example to demonstrate the power and accessibility JSON offers to developers.

The first example is to demonstrate the power and the accessibility JSON offers to developers. This is a JavaScript code designed to make things easier for the -new to JSON- developer:

function User(fName, lName, age, friends)
{
    var UserObject = {
        FirstName: fName,
        LastName: lName,
        Age: age,
        Friends: [],
        IsUnderAge: function()
        {
            return this.Age > 21 ? true : false;
        }
    };

    var FriendsCounter = 0;
    for (var frnd in friends)
    {
        UserObject.Friends[FriendsCounter] = friends[frnd];
        FriendsCounter++;
    }

    return UserObject;
}

This is the constructor. Same as in every OOP language, each object needs to have constructors.

Now, let's say I let a user named Igor fill an information form containing the following fields:

  1. First Name
  2. Last Name
  3. Age
  4. Friends - each friend will have the same fields.

On the "Submit" button, I have a call for a "CreateUser" function which will take the needed fields (using jQuery - but that's for another post) and send to the User constructor.

function createUser()
{
    var IgorsFriends = [];
    IgorsFriends[0] = new User("Uri", "GamingTech", 29, []);
    IgorsFriends[1] = new User("Sergey", "GamingTech", 35, [
        new User("Noam", "GamingTech", 27, [])
    ]);
    
    var Igor = new User("Igor", "GamingTech", 33, IgorsFriends);
}

The outcome of this function will be a variable named Igor which will have the following attributes:

  • First Name
  • Last Name
  • Age

The following methods:

  • IsUnderAge

And the following arrays:

  • Friends - which will contain a list of friends as User objects.

Good luck!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DevAffair
Team Leader Sports Betting Tech
Israel Israel
No Biography provided
Follow on   Twitter

Comments and Discussions

 
Questionamit Pinmemberpradeep rawat20-Jun-11 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 13 Jun 2011
Article Copyright 2011 by DevAffair
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid