JSON in JavaScript

JSON stands for JavaScript Object Notation that is a language independent text format which is fast and easy to understand. That means it is really very simple and easy to learn without sparing much time. In another words we can say that JavaScript Object Notation is a lightweight data-interchange format that is completely language independent but with some conventions. So in this section of JSON tutorial we are going to discuss JSON with JavaScript. Creating Object in JavaScript using JSON We can create objects in JSON with JavaScript in many ways : 1. "var JSONObjectName ={};" will create an empty object. 2. "var JSONObjectName= new Object();" will create a new Object. 3. "var JSONObjectName = { "name ":"amit", "age":23}; will create an Object with attribute name which contains value in String and age with numeric value. Now by creating this object we can access attributes by only "." operator. Here is the full example code for creating an Object in JavaScript using JSON:

ObjectJavaScript-JSON.htm
<html> <head> <title> Object creation in JSON in JavaScript </title> <script language="javascript" > : "Amit", var JSONObject = { "name" "address" : "B-123 Bangalow", "age" : 23, "phone" : "011-4565763", "MobileNo" : 0981100092 }; document.write("<h2><font color='blue'>Name</font>::" +JSONObject.name+"</h2>"); document.write("<h2><font color='blue'>Address</font>::" +JSONObject.address+"</h2>"); document.write("<h2><font color='blue'>Age</font>::"

+JSONObject.age+"</h2>"); document.write("<h2><font color='blue'>Phone No.</font>::" +JSONObject.phone+"</h2>"); document.write("<h2><font color='blue'>Mobile No.</font>::" +JSONObject.MobileNo+"</h2>"); </script> </head> <body> <h3>Example of object creation in JSON in JavaScript</h3> </body> </html>

Output:

To run this JavaScript and JSON example you have to just run this ".htm" file on your browser.

Maths[1]. "Science" : [ { "Name" "Marks" "age" "Name" "Marks" "age" ] } // Printing all array values : "Amit".Maths[1].Maths[1]" and then we can access elements of this array as "students. : 65. Here is the full example code for JavaScript-JSONArray. : "Sandeep". JavaScript-JSONArray. 56.Creating Array Objects in JavaScript with JSON In the previous section of JavaScript-JSON tutorial you have known that how to create an object and now in this tutorial we have provided you the way array of objects are declared in JavaScript-JSON.Name" for name and "students. Now we can access these objects value in the following way: "students. marks and age of two students. Now to access first element of the Maths array we can write it as "students. "Santosh". : 23 }. : 67. 27 }. In our example file we have created an object "students" which contains two array objects "Maths" and "Science" containing name. 41 } // First Element // Second Element .Science" for accessing Science array object.htm file.htm <html> <head> <title> Array JSON-JavaScript Example </title> <script language="javascript" > var students = { "Maths" : [ {"Name" "Marks" "age" { "Name" "Marks" "age" ].Marks" for marks of the first student in Maths and so on. : 21 } // First element // Second element : : : : : : "Shaili".Maths" for accessing Maths array and "students. 78.

writeln("</table>").Science[i].Science[i]. document. document.writeln("<td>").var i=0 document. } document.writeln("<tr><td><B>Marks</B></td><td width=50>" +students.i<students.writeln("</td>").i<students. </script> </head> <body> Using Array of objects via JSON in JavaScript </body> </html> Output: To run this example create JavaScript-JSONArray.writeln("</tr></table>").age +"</td></tr>").writeln("<table border='0' width=100 >").Marks +"</td></tr>").length.writeln("<tr><td><B>Name</B></td><td width=50>" +students.writeln("<td>"). document.writeln("<tr><td><B>Marks</B></td><td width=50>" +students. .Name+"</td></tr>").Maths[i].i++) { document.writeln("</td>").age +"</td></tr>"). document. } for(i=0.writeln("<table border='0' width=100 >").htm and run it on browser for output.length. for(i=0.writeln("<tr><td><B>Age</B></td><td width=50>" +students. document.Marks +"</td></tr>").writeln("<tr><td><B>Name</B></td><td width=50>" +students.Maths[i].i++) { document. document. document. document.Maths[i]. document.Name+"</td></tr>").writeln("<table border='1'><tr>"). document.writeln("<tr><td><B>Age</B></td><td width=50>" +students.Science[i].Maths. document.Science. document.writeln("</table>").

Creating Message in JSON with JavaScript In previous section you have studied about the JSON in JavaScript's some basic concepts of creating a simple object and creating an array of objects.js" file first. : 23 }. : 21 } // First element // Second element . Again we have created an array object and pushed one array data into it.js"></script> <script language="javascript" > var students = { "Maths" : [ { "Name" "Marks" "age" { "Name" "Marks" "age" ]. After this we have created an object variable students which contains two array objects . Here is the example code of CreatingMessage.htm : CreatingMessage. Now we are going to discuss how to create a message with JSON in JavaScript. : "Sandeep". Message is then created by converting array object to string by using the function "toJSONString()" . "Science" : [ : "Amit". : 65. In this example of creating message in JSON with JavaScript we have included "json2.htm <html> <head> <title> Creating Message using JSON in JavaScript </title> <script language="javascript" src="json2. : 67.

js 2008-05-25 Public Domain No warranty expressed or implied.js" file code: /* json. .Maths.js See http://www.push(students.org/js. 78. It must not contain any cyclical references.toJSONString() number.toJSONString() date.html This file adds these methods to JavaScript: array.org/json2.toJSONString()).Maths[i]. Illegal values will be excluded.Maths[i].toJSONString() object. You can add a toJSONString method to any date object to get a different representation.toJSONString(whitelist) string. arrayObject.i<students.length. The default conversion for dates is to an ISO string.JSON. 41 } // First Element // Second Element } // Printing array elements values var i=0 var arrayObject = new Array().toJSONString() These methods produce a JSON text from a JavaScript value.Maths[i]. } alert("Welcome to JSON Message Example ").push(students. arrayObject. "Santosh".toJSONString(whitelist) boolean.age).i++) { arrayObject.push(students. </script> </head> <body> Message creation using JSON in JavaScript </body> </html> Here is the "json2. for(i=0.{ "Name" "Marks" "age" { "Name" "Marks" "age" ] : : : : : : "Shaili". 56.Name).JSON. alert(arrayObject.Marks). 27 }. This file has been superceded by http://www. Use at your own risk.

and its return value is used instead of the original value. It can be a function or an array.indexOf('date') >= 0 ? new Date(value) : value. replacer. then structure is not modified. The optional filter parameter is a function which can filter and transform the results. This method produces a JSON text from a JavaScript value. myData = text. Example: // Parse the text.parseJSON(function (key.com/blog/2006/09/26/for-in-intrigue/ This file creates a global JSON object containing two methods: stringify and parse. value) { return key. This file will break programs with improper for. JSON. space) value any JavaScript value. it contains the characters used to indent at each level. it will specify the number of spaces to indent at each level. When an object value is found. replacer an optional parameter that determines how object values are stringified for objects without a toJSON method. See http://yuiblog. If it is omitted.stringify(value.in loops. If it is a number. If it is a string (such as '\t' or '&nbsp. If it returns undefined then the member is deleted.parseJSON(filter) This method parses a JSON text to produce an object or array.. string. space an optional parameter that specifies the indentation of nested structures. the text will be packed without extra whitespace.'). If it returns what it received. usually an object or array. keys in objects not found in the whitelist are excluded. }). If a key contains the string 'date' then // convert the value to a date.The object and array methods can take an optional whitelist argument. If it is provided. A whitelist is an array of strings. if the object contains a toJSON . It receives each of the keys and values. It can throw a SyntaxError exception.

return n < 10 ? '0' + n : n. If the replacer parameter is an array. then that string will be used for indentation. If your method returns undefined.getUTCHours()) + ':' + f(this. this would serialize Dates as ISO strings. If the space parameter is a non-empty string. JSON. Values that do not have JSON representations. }. You can provide an optional replacer method. It will be passed the key and value of each member. Such values in objects will be dropped.getUTCMonth() + 1) + '-' + f(this. You can use a replacer function to replace those with JSON values. For example. The toJSON method will be passed the key associated with the value. and this will be bound to the object holding the key. Date.getUTCDate()) + 'T' + f(this. If the space parameter is a number.prototype.getUTCMinutes()) + ':' + f(this. then it will be used to select the members to be serialized. Example: . It filters the results such that only members with keys listed in the replacer array are stringified.getUTCFullYear() + '-' + f(this. then the indentation will be that many spaces.getUTCSeconds()) + 'Z'.stringify(undefined) returns undefined. The value that is returned from your method will be serialized. such as undefined or functions. then the member will be excluded from the serialization. in arrays they will be replaced with null.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. or undefined if nothing should be serialized.method. will not be serialized. } return this. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. with this bound to the containing object. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized. its toJSON method will be called and the result will be stringified.

null.1. if (typeof value === 'string' && . }). // text is '[\n\t"e". If it returns undefined then the member is deleted. // text is '["e". function (key. function (key.{"pluribus":"unum"}]' text = JSON.UTC(+a[1]. myData = JSON. myData = JSON.parse(text. if (typeof value === 'string') { a= /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\. {pluribus: 'unum'}]). // text is '["Date(---current time---)"]' JSON.parse('["Date(09/09/2001)"]'. value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value.\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON. If it returns what it received. value) { var a.stringify([new Date()]. The optional reviver parameter is a function that can filter and transform the results. +a[4]. }). '\t'). value) { var d. +a[3]. It can throw a SyntaxError exception.stringify(['e'. +a[5]. +a[6])). Values that look like ISO date strings will // be converted to Date objects.text = JSON.exec(value). reviver) This method parses a JSON text to produce an object or array. Example: // Parse the text. if (a) { return new Date(Date. +a[2] . It receives each of the keys and values.\d*)?)Z$/. } } return value. {pluribus: 'unum'}].stringify(['e'. then the structure is not modified. function (key. and its return value is used instead of the original value.parse(text.

IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*jslint evil: true */ /*global JSON */ /*members "". join. modify. getUTCMinutes. }). hasOwnProperty. See http://javascript. getUTCHours.com/jsmin. } } return value. push. "\b".slice(0. replace. You are free to copy. test. slice. parse. "\f". lastIndex. -1)). JSON = function () { function f(n) { . toJSONString. It is expected that these methods will formally become part of the JavaScript Programming Language in the Fourth Edition of the ECMAScript standard in 2008. toString */ if (!this. stringify. parseJSON. getUTCMonth. toJSON. "\r". This is a reference implementation. 5) === 'Date(' && value.JSON) { // Create a JSON object only if one does not already exist. getUTCSeconds. charCodeAt.slice(-1) === ')') { d = new Date(value.html USE YOUR OWN COPY. call. We create the // object in a closure to avoid global variables. length. "\\". prototype. "\"". propertyIsEnumerable. This code should be minified before deployment.slice(5.crockford. getUTCFullYear. "\t". or redistribute. if (d) { return d. JSON. "\n". getUTCDate.value.

rep. } .getUTCSeconds()) + 'Z'.prototype. }.replace(escapeable.getUTCFullYear() + '-' + f(this. // Otherwise we must also replace the offending characters with safe escape // sequences. and no // backslash characters. '\r': '\\r'.toJSON = function (key) { return this. return n < 10 ? '0' + n : n.getUTCMinutes()) + ':' + f(this. function quote(string) { // If the string contains no control characters. indent.lastIndex = 0. '"' : '\\"'. gap.test(string) ? '"' + string. meta = { // table of character substitutions '\b': '\\b'. no quote characters. if (typeof c === 'string') { return c. return escapeable. '\n': '\\n'. '\t': '\\t'.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.// Format integers to have at least two digits. function (a) { var c = meta[a].getUTCMonth() + 1) + '-' + f(this. escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600\u0604\u070f\u17b4\u17b5 \u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g. escapeable. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5 \u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g. } Date. then we can safely slap some quotes around it. '\f': '\\f'. '\\': '\\\\' }.

// The member key. }) + '"' : '"' + string + '"'. if (typeof rep === 'function') { value = rep. } // If we were called with a replacer function. } // What happens next depends on the value's type. // The loop counter. } function str(key. key. case 'boolean': . switch (typeof value) { case 'string': return quote(value). then call the replacer to // obtain a replacement value.return '\\u' + ('0000' + (+(a. return isFinite(value) ? String(value) : 'null'. value). case 'number': // JSON numbers must be finite. // If the value has a toJSON method. call it to obtain a replacement value. length.slice(-4). k. partial. holder) { // Produce a string from holder[key].toJSON(key). mind = gap.toString(16)).toJSON === 'function') { value = value. // The member value. Encode non-finite numbers as null. v.charCodeAt(0))).call(holder. var i. value = holder[key]. if (value && typeof value === 'object' && typeof value.

separated with commas. typeof null is 'object'. if (typeof value. case 'object': // Due to a specification blunder in ECMAScript. if (!value) { return 'null'. we'll treat it as an array.length === 'number' && !(value. convert it to a string. Use null as a placeholder // for non-JSON values. gap += indent. } // Make an array to hold the partial results of stringifying this object value. length = value. // If the type is 'object'. Note: // typeof null does not produce 'null'.\n' + gap) + '\n' + . return String(value).length === 0 ? '[]' : gap ? '[\n' + gap + partial.join('. The case is included here in // the remote chance that this gets fixed someday. v = partial. i < length. // so watch out for that case. value) || 'null'. we might be dealing with an object or an array or // null. Stringify every element. i += 1) { partial[i] = str(i. } // Join all of the elements together. for (i = 0. and wrap them in // brackets.length. partial = [].propertyIsEnumerable('length'))) { // The object is an array. // If the object has a dontEnum length property.case 'null': // If the value is a boolean or null.

gap = mind.join('. return v.') + ']'. for (k in value) { if (Object. if (typeof k === 'string') { v = str(k.length === 0 ? '{}' : gap ? '{\n' + gap + partial. i < length.\n' + gap) + '\n' + mind + '}' : '{' + partial. i += 1) { k = rep[i]. for (i = 0.join('.push(quote(k) + (gap ? ': ' : ':') + v).push(quote(k) + (gap ? ': ' : ':') + v). if (v) { partial.hasOwnProperty. // and wrap them in braces. rep). gap = mind. } } } } else { // Otherwise.') + '}'. separated with commas. k)) { v = str(k. value.mind + ']' : '[' + partial. use it to select the members to be stringified. .length. rep).join('. if (v) { partial. v = partial. } } } } // Join all of the member texts together. if (rep && typeof rep === 'object') { length = rep. value.call(value. iterate through all of the keys in the object. } // If the replacer is an array.

var i. return { stringify: function (value. gap = ''. it must be a function or an array. // If the space parameter is a number. make an indent string containing that // many spaces. // A default replacer method can be provided. // Otherwise. or an array of strings that will select the keys. and returns a JSON text. Use of the space parameter can // produce text that is more easily readable. throw an error. } else if (typeof space === 'string') { indent = space. i += 1) { indent += ' '.return v. if (replacer && typeof replacer !== . space) { // The stringify method takes a value and an optional replacer. i < space. The replacer can be a function // that can replace values. } // If the space parameter is a string. replacer. rep = replacer. } } // Return the JSON object containing the stringify and parse methods. and an optional // space parameter. it will be used as the indent string. } // If there is a replacer. indent = ''. if (typeof space === 'number') { for (i = 0.

return str(''. // Return the result of stringifying the value. } // Parsing happens in four stages. value).length !== 'number')) { throw new Error('JSON. k). and returns // a JavaScript value if the text is a valid JSON text. if (v !== undefined) { value[k] = v.hasOwnProperty.'function' && (typeof replacer !== 'object' || typeof replacer. key. } } } } return reviver. function walk(holder. var j.call(value. parse: function (text.call(holder. v. }. value = holder[key]. var k.stringify'). } else { delete value[k]. if (value && typeof value === 'object') { for (k in value) { if (Object. reviver) { // The parse method takes a text and an optional reviver function. In the . key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. k)) { v = walk(value. } // Make a fake root object containing our value under the key of ''. {'': value}).

we delete all // open brackets that follow a colon or comma or that begin the text.toString(16)). replace(/(?:^|:|. then the text is safe for eval. }).charCodeAt(0))).replace(/\\(?:["\\\/bfnrt]|u[0-9a-fAF]{4})/g.test(text)) { text = text.replace(cx. test(text. we // replace all simple value tokens with ']' characters. '@'). Finally.:{}\s]*$/. we replace certain // Unicode characters with escape sequences.lastIndex = 0. If that is so. // we look to see that the remaining characters are only whitespace or ']' or // '. if (/^[\]. cx. We are especially concerned with '()' and 'new' // because they can cause invocation. we run the text against regular expressions that look // for non-JSON patterns. if (cx. First we // replace the JSON backslash pairs with '@' (a non-JSON character). ''))) { . function (a) { return '\\u' + ('0000' + (+(a. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. and '=' because it can cause mutation. } // In the second stage.\d*)?(?:[eE][+\-]?\d+)?/g. either silently deleting them.slice(4). ']'). // But just to be safe.)(?:\s*\[)+/g. Second. JavaScript handles many characters // incorrectly.first stage. replace(/"[^"\\\n\r]*"|true|false|null|?\d+(?:\. we want to reject all unexpected forms. or treating them as line endings. Third.' or ':' or '{' or '}'.

prototype.parseJSON = function (filter) { return JSON. filter). }. // These forms are obsolete. filter).prototype. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. passing // each name/value pair to a reviver function for possible transformation.stringify(this. then a SyntaxError is thrown. throw new SyntaxError('JSON. } }. } . }(). if (!Object. '') : j.toJSONString = function (filter) { return JSON. // In the optional fourth stage. j = eval('(' + text + ')').stringify and // JSON. }.prototype.parse be used instead. we recursively walk the new structure.parse(this. } // If the text is not JSON parseable. return typeof reviver === 'function' ? walk({'': j}.// In the third stage we use the eval function to compile the text into a // JavaScript structure. Object. It is recommended that JSON.toJSONString) { Object.parse'). } // Augment the basic prototypes if they have not already been augmented. We wrap the text // in parens to eliminate the ambiguity.

To run this example open the CreateMessage.htm on the browser and the output on the browser will look like this: Array object converted to string by using the toJSONString() function will be displayed in the alert() message as follows: .

We can parse the message with JSON in JavaScript by using the method "String. Here is the full example code for ParseMessageJSON.parseJSON(filter)". This method internally uses the JavaScript's method eval() to parse messages. It parses the JSON message to an string or object. "age" : 23 }.htm <html> <head> <title>Parsing Message using JSON in JavaScript</title> <script language="javascript" src="json2.js"></script> <script language="javascript" > var students = { "Maths" : [ { "Name" : "Amit". // First element "Marks" : 67. { "Name" : "Sandeep".htm as follows: ParseMessageJSON. // Second element "Marks" : 65. The parameter "filter" is optional in this method which is used to filter message or transform their results. "age" : 21 } ] .Parsing a message in JavaScript with JSON In the previous section of example we have studied how to create message in JSON in JavaScript and now we will come to know that how we can parse the message in JSON in JavaScript.

Maths[i]. } alert("Parsing JSON Message Example "). arrayObject.push(students.js file included with our ParseMessageJSON. File "json2.parseJSON()).push(students. alert(arrayObject.js" is as same as in our previous example of "creating message in JavaScript with JSON" .i<students.i++) { arrayObject. </script> </head> <body> Parsing Message using JSON in JavaScript </body> </html> To run this example we need to have json2.Maths[i].length. Output: Run ParseMessageJSON.Maths.} // Printing Maths array values in the alert message var i=0 var arrayObject = new Array(). for(i=0.Name).toJSONString(). arrayObject.Maths[i].age).htm file.htm file on your browser.push(students. It will generate output on your browser as follows: .Marks).

JSONObject example in Java In the previous section of JSON tutorials you have seen how JSON can be used with JavaScript to create objects and arrays. JSON-lib also requires following "JAR" files: 1. you have also studied how to parse and create messages with JSON in JavaScript. Now in this part you will study how to use JSON in Java.2.jar commons-beanutils. 4. 5. commons-lang. 3. 6. 2.jar commons-collections. To have functionality of JSON in java you must have JSON-lib.jar ezmorph.jar json-lib-2.2-jdk15.jar .jar commons-logging.

java is as follows: FirstJSONJava. object."Amit").put("nickname". For using JSONObject class we have to import following package "net.JSONObject. In this example we are going to use JSONObject class for creating an object of JSONObject and then we will print these object value. collections.new Double(40)).Marks".put("Scored".new Integer(100)).println(object). java arrays and XML to JSON and then for retransforming them back to beans. collections. maps.java import net.put("name".JSON-lib is a java library for that transforms beans.You will get following output: Output: . } } To run this example you have to follow these few steps as follows: y y y y Download JSON-lib jar and other supporting Jars Add these jars to your classpath create and save FirstJSONJava. object. object.java Compile it and execute .sf. object.sf.json". object.out.put("Max.Marks"."Amit Kumar").put("Min.json.67)).new Double(66. To add elements in this object we have used put() method. Here is the full example code of FirstJSONJava. public class FirstJSONJava { public static void main(String args[]){ JSONObject object=new JSONObject(). maps and others. System.

commons-lang.NULL objects. arrayObj.jar commons-logging. } } .add("Amit Kumar").add("Scored")."JSONArray" example in Java In this part of JSON tutorial you will study how to use JSONArray in Java.out.add(new Double(66.Marks"). System.add(new Integer(100)).JSONArray. collections. JSONArray.sf.67)). 5. 2.json". arrayObj. arrayObj.It may consists of Boolean. To have functionality of JSON in your java program you must have JSON-lib. 4.java import net.add("name :").jar ezmorph. java arrays and XML to JSON and then for retransforming them back to beans.jar json-lib-2. Number and String or the JSONObject. arrayObj. arrayObj.Marks :"). JSONObject.add("Min. arrayObj.jar commons-beanutils. public class JSONJavaArray { public static void main(String args[]){ JSONArray arrayObj=new JSONArray(). JSONArray is a sequential and ordered way of collection values. 3.2-jdk15.add(new Double(40)). 6. Here is the full example code of JSONJavaArray. arrayObj.java as follows: FirstJSONJava. In this example we are going to use JSONArray for creating an object of JSONArray and then we will print this array object . To add elements in this object we have used add() method.println(arrayObj). maps and others.jar commons-collections.add("Max. maps. JSON-lib also requires following "JAR" files: 1.json.2.sf. For using JSONArray class we have to import package "net.jar JSON-lib is a java library for that transforms beans. arrayObj. collections.

ezmorph. public class JSONServlet extends HttpServlet{ public void doGet(HttpServletRequest request.jar.servlet. Here is the example code of JSONServlet. Now in this example we will tell you how to use JSON classes for creating Servlet.java Compile it and execute .jar. To have functionality of JSON in your application you must have JSON-lib and its supported jar files.2.IOException{ . javax.You will get following output: Output: JSON and Servlet example In the previous section of JSON-Java example you have learned how to create a java class by using JSON classes. net.To run this example you have to follow these few steps as follows: y y y y Download JSON-lib jar and other supporting jars Add these jars to your classpath create and save JSONJavaArray. commons-logging. commons-collections.json.jar and json-lib2.io.sf.java import import import import java. javax.*.java as follows: JSONServlet. In this example we have created an object of JSONArray and then we have added elements into this array by using the method add().http.jar.jar.servlet. These are: commons-lang.*.jar.2-jdk15. commonsbeanutils.HttpServletResponse response) throws ServletException.JSONArray.*.

arrayObj.add("Scored").com/xml/ns/javaee" xmlns:xsi="http://www.add("19-12-1986"). arrayObj.println(arrayObj).add(24).w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.67)).println(arrayObj.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java. out.com/xml/ns/javaee/web-app_2_5.i<arrayObj. for(int i=0. .size(). arrayObj.JSONArray arrayObj=new JSONArray().xsd" version="2.sun. arrayObj.add("Amit Kumar"). arrayObj.java class compile JSONServlet and place it into WEB-INF/classes directory Download JSONLibraries and place it into Tomcat's lib directory Start Tomcat Webserver and type http://localhost:8080/JSON/JSONServlet into browser's address bar you will have following output on your browser.5"> <servlet> <servlet-name>JSONServlet</servlet-name> <servlet-class>JSONServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JSONServlet</servlet-name> <url-pattern>/JSONServlet</url-pattern> </servlet-mapping> </web-app> To run this example follow this step by step procedure: y y y y create a JSONServlet. PrintWriter out = response.i++){ out.com/xml/ns/javaee http://java.getString(i)).add("MCA"). } } } We have to do corresponding servlet mapping into web.add(new Double(66.sun. arrayObj.xml as given below: <?xml version="1.sun.getWriter().

arrayObj. commons-collections. To get string values of array object we have used getString(index int) method of JSONArray. commons-logging. arrayObj.json.add("19-12-1986"). arrayObj.jsp as follows: JSON-JSPExample. ezmorph. These are: commons-lang.jar.jar.jar and json-lib-2. Now in this example we will tell you how to use JSON to use it into JSP pages.jar. commons-beanutils. In this example we have created an object of JSONArray and then we have added elements into this array by using the method add().2-jdk15. .JSONArray" %> <% JSONArray arrayObj=new JSONArray(). To have functionality of JSON in your application you must have JSON-lib and its supporting jar files as well.jar.sf.add("Amit Kumar").2.jar.Output: JSON-JSP example In the previous section of JSON-Servlet example you have learned how to create a servlet class by using JSON classes. It returns string value of that array object's index.jsp <%@ page language="java" import="net. Here is the example code of JSON-JSPExample.add(24).add("MCA"). arrayObj.

%> <h2>Array Object is =></h2> <%=arrayObj%> <br><hr> <% for(int i=0.size(). Output: .add("Scored").i++){ %> <%=arrayObj.getString(i)%> <% } %> To run this example follow this step by step procedure: y y y y create a JSON-JSPExample.add(new Double(66.67)). arrayObj.arrayObj.jsp file and place it into WEB-INF directory Download JSONLibraries and place it into Tomcat's lib directory Start Tomcat Webserver and type http://localhost:8080/JSON/JSON-JSPExample.i<arrayObj.jsp into browser's address bar you will have following output on your browser.

Sign up to vote on this title
UsefulNot useful