Ridhima Ridhima - 5 months ago 18
Javascript Question

How to create a json object in jsp?

How to create a json object in jsp?

var jsonObj = {
"firstname": "test",
"lastName": "test",
"email": "test",
"mobile": "test",
"place": "test",
"country": "test"
};

alert(jsonObj.length);


This prints "undefined" for length.




var json = {"person":
{
"p1":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},

"p2":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},

"p3":
{"home":
{"address":0,
"phoneNumber":0
},
"office":
{"address":0,
"phoneNumber":0
}
},
},

"msg":"People data"
} ;


Suppose this is my json object.
I want to run a loop and iterate through the values..

alert("json length = " + Object.keys( json ).length); //2
alert("keys in json : " + Object.keys(json)); //person,msg

var people = json.person;
var personLen = Object.keys( people ).length; //3


Now I want to run a loop and get the values inside p1, p2, p3 ..

for(i=0; i<people; i++) {

var person = people[i]; //but this doesnt work

}


How do I get these values using loop?

Answer

This prints "undefined" for length.

Because it doesn't have property named length and it is not an array which would have a built-in property length.

If you want to get the number of properties in this object then try

Object.keys( jsonObj ).length
Comments