Iterate over a JSON object

One of the most useful advantages of the JSON format is that it is browser friendly. You donot need to write complicated code for navigating or iterating over a JSON structure. In this post, I will show you how to iterate over a JSON object.

Assume that you are having the following JSON object.

<script type="text/javascript">
var personStr = "{\"Name\":\"Hazem Saleh\",\"Occupation\":\"Software Engineer\",\"Nationality\":\"Egyptian\",\"Age\":\"102\"}";

var personObject = eval("(" + personStr + ")");

You may notice that I put the JavaScript String between parentheses. This is mandatory to avoid the json invalid label browser error.

if you want to simply iterate over the JSON object you should use the standard JavaScript for in loop as follows.

<script type="text/javascript">
for (var key in personObject) {
  if (personObject.hasOwnProperty(key)) {
    alert(key + " -> " + personObject[key]);

I wish that this tip can be helpful to you.

Java Web Development Introductory Course For Beginners Slides

I had written a set of slides to be an introduction for guys who wish to start writing web applications with Java.

These slides cover the following topics in a simple way:

1. The Servlet Model.

2. Web Applications Structure.

3. The Web container Model.

4. JSP.

5. JSP Standard Actions, EL.

6. JSTL.

7. Classic Tag Libraries.

You will find samples for each lesson in the zip file. I wish you will learn from this course.

Java encoding similiar to JavaScript encodeURIComponent

You may have a REST service that returns an encoded output to a JavaScript client which decodes this output in the client side. Unfortunately, this scenario will not always work because of the mismatch between both the Java encode() API and the JavaScript encodeURIComponent().

To be able to make the encode() behavior equivalent to the JavaScript encodeURIComponent(), all what you should do is the following String replacements.

public static String encodeURIComponent(String component)   {     
	String result = null;      
	try {       
		result = URLEncoder.encode(component, "UTF-8")   
			   .replaceAll("\\%28", "(")                          
			   .replaceAll("\\%29", ")")   		
			   .replaceAll("\\+", "%20")                          
			   .replaceAll("\\%27", "'")   			   
			   .replaceAll("\\%21", "!")
			   .replaceAll("\\%7E", "~");     
	catch (UnsupportedEncodingException e) {       
		result = component;     
	return result;   

After that you can safely decode the output in the client side using the JavaScript decodeURIComponent().