/java-script/

Json Object in JavaScript

2012-08-21 20:09:47

Simple json.



<script>

        var jsonString = '['+
                            '{&quot;name&quot;:&quot;Google&quot;,&quot;www&quot;:&quot;www.google.com&quot;},'+
                            '{&quot;name&quot;:&quot;Facebook&quot;,&quot;www&quot;:&quot;www.facebook.com&quot;},'+
                            '{&quot;name&quot;:&quot;Btbw&quot;,&quot;www&quot;:&quot;www.btbw.pl&quot;}'+
                         ']';

        var jsObject = function(jsonString){

            this.dataObj = JSON.parse(jsonString);

            this.getLength = function(){
                return this.dataObj.length;
            }

            this.getObjectByNum = function(_nr){
                return this.dataObj[_nr];
            }

            this.getAllObject = function(){
                return this.dataObj;
            }

            this.getParamByNumObjByKey = function(_nr,_key){
                return this.dataObj[_nr][_key];
            }

            this.getLengthParamObjectByNum = function(_nr){
               var keys = [];
               for(var key in this.dataObj[_nr]){
                  keys.push(key);
               }
               return keys.length;
            }

            this.getNameParamFromObjByNum = function(_nr,_keyNr){
               var keys = [];
               for(var key in this.dataObj[_nr]){
                  keys.push(key);
               }
               return _keyNr === undefined ? keys : keys[_keyNr];
            }

        }

        var json = new jsObject(jsonString);

        console.log(json.getLength());

        console.log(json.getAllObject());

        console.log(json.getObjectByNum(0));
        console.log(json.getObjectByNum(1));
        console.log(json.getObjectByNum(2));


        console.log(json.getLengthParamObjectByNum(0));

        console.log(json.getNameParamFromObjByNum(0));
        console.log(json.getNameParamFromObjByNum(0,1));

        console.log(json.getParamByNumObjByKey(0,'name'));
        console.log(json.getParamByNumObjByKey(0,'www'));

    </script>