How To Parse JSON in Javascript – Read a JSON File With JQuery

November 29, 2009 · Leave a Comment
Filed under: Featured, JavaScript, JQuery 

JQuery has a neat function that allows us to read external and local JSON files.

jQuery.getJSON( url, [data], [callback] )

The first parameter of this function, the URL you are planning to read, is required. The second parameter is used if you need to POST data to the URL. Last but no least, the callback function, although not required, is almost always necessary.

Important: The URL can be to a local or external file. If the file is in another server the URL must contain a callback variable. You’ll see how this works in the next paragraphs.

The Json File

Rather than making my own JSON file, like I’ve done for previous XML and JSON tutorials, I’ve decided that we’ll use Twitter’s search API this time.

Twitter’s search API has many different search options, but you only need to know about the callback and query “q” options.

Most basic Twitter search URL.

http://search.twitter.com/search.json?callback=foo&q=google+wave

Although required in the URL, your script does not have to have a callback function or variable. Just give the callback a value of “?” like this.

http://search.twitter.com/search.json?callback=?&q=google+wave

Important: Different APIs have different callback URL names, flickr’s API for example uses “jsoncallback” instead of “callback” in the URL. Always read the API docs very carefully.

Now that you know what it takes to query Twitter, take a look a sample response.

{"results":[
     {"text":"@twitterapi  http:\/\/tinyurl.com\/ctrefg",
     "to_user_id":396524,
     "to_user":"TwitterAPI",
     "from_user":"jkoum",
     "id":1478555574,
     "from_user_id":1833773,
     "iso_language_code":"nl",
     "source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
     "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"}],
     "since_id":0,
     "max_id":1480307926,
     "refresh_url":"?since_id=1480307926&q=%40twitterapi",
     "results_per_page":15,
     "next_page":"?page=2&max_id=1480307926&q=%40twitterapi",
     "completed_in":0.031704,
     "page":1,
     "query":"%40twitterapi"}]
}

This response only returned one result but you need not worry about that.

In this API the set of results begin with “[” and end with “]”. Every time you see this symbols it means that you loop through the set in them.

Retrieving The Results

Let’s begin building our JSON reading script. This script will be a twitter search script, so we are going to need a text box, a button and a div where we show the results.

<input type="text" id="query" /><button>Search</button>
<div id="results"></div>



The JQuery part will have the following structure

$(document).ready(function(){
    // twitter api's base url
    var url="http://search.twitter.com/search.json?callback=?&q=";
    // we'll store the search term here
    var query;

    // when the user clicks the button
    $("button").click(function(){
          // get value in the search box and store it in the variable
          query=$("#query").val();
          // get the json file
    });
});

Okay, we have the basic set up, it’s now time to build the getJSON part.

Our URL parameter will be the URL concatenated with the query (url+query). Since we are not posting data we don’t need the second parameter. The function getJSON returns a JSON object which we will use as parameter for the callback function.

// get the json file
 $.getJSON(url+query,function(json){
    // this is where we can loop through the results in the json object
});

Looping Through The Results

Notice that we passed an object called “json” to the callback function, you can change the name of this object but I think json makes sense. This object now contains all the json data we need, all we need to to now is loop through the results sent from twitter.

// this is where we can loop through the results in the json object
$.each(json.results, function(i,tweet){
     // this is where we do what we want with the tweet
});

Let’s break down the loop. the first parameter “json.results” refers to the array in the object we want to loop through, since the only array in the json response from the Twitter search API is “results” we say json.results. The second parameter, the function, has two parameters and you can change the name of them if you want to, I used “i” and “tweet”.

The the “i” refers to the current number of loops and you could use if for example to display the number of results you got from the query. The “tweet” refers to the current tweet, so you can refer to any of the following keys by prepending the word “tweet” before them.

{
"text":"@twitterapi  http:\/\/tinyurl.com\/ctrefg",
     "to_user_id":396524,
     "to_user":"TwitterAPI",
     "from_user":"jkoum",
     "id":1478555574,
     "from_user_id":1833773,
     "iso_language_code":"nl",
     "source":"<a href="http:\/\/twitter.com\/">twitter<\/a>",
     "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production\/profile_images\/118412707\/2522215727_a5f07da155_b_normal.jpg",
     "created_at":"Wed, 08 Apr 2009 19:22:10 +0000"
}

To get the username from which the tweet originated you would use tweet.from_user , to get the actual tweet you would use tweet.text.

Let’s put the profile image and tweet in our div tag.

// this is where we can loop through the results in the json object
$.each(json.results,function(i,tweet){
     // this is where we do what we want with each tweet
    $("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
});

The full script

<input type="text" id="query" /><button>search</button><br />
<div id="results">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://search.twitter.com/search.json?callback=?&q=';
var query;
	$('button').click(function(){
		query=$("#query").val();
		$.getJSON(url+query,function(json){
			$.each(json.results,function(i,tweet){
			   $("#results").append('<p><img src="'+tweet.profile_image_url+'" widt="48" height="48" />'+tweet.text+'</p>');
			});
		});
	});
});
</script>

More JSON API’s

Here’s a list of some API’s that return JSON for you to pratice. Let me know if you of more.
Flickr
bit.ly
Best Buy

Struts2 + JSON to achieve the return of objects and a list of AJAX

October 29, 2009 · Leave a Comment
Filed under: Featured, JAVA 

JSON is a plug-in, it allows us to call in the asynchronous JavaScript in Action, it provides a return json result type (ResultType), as long as the specified type for Action

return json result type, then the outcome of this response does not need to return to any view layer, JSON to Action in the sequence status information into a prescribed format JSON data and return the data

To JAVASCRIPT, to be completed this interactive AJAX applications.
JSON plug-ins to the application, first of all need to

http://code.google.com/p/jsonplugin/downloads/list

Download the latest plug-in JSON, I was here to download jsonplugin –

0.33.jar, the document Kaodao LIB directory WEB project, of course, also need to download Struts2 libraries, can http://struts.apache.org/download.cgi # struts2014

Here to download, extract after download, the WEB project JAR Kaodao LIB directory, should not be less than the following JAR file (struts2-api-2.0.5.jar, struts2-core-2.0.5.jar,

ognl-2.6.9.jar, xwork-2.0.0.jar, commons-logging-1.1.jar, freemarker-2.3.8.jar, depending on the specific version of the file name may be), then we can write in an application

To test, divided into the two-step routines to write, the first step to achieve the return of a result object, the second step to achieve returns a results list, first of all look at the results back to the realization of the object.
We need to create a JavaBean for the value object to the user’s basic data package into the entity objects and results in the results list will be used to
Users.java code is as follows:

package com.jsontostruts2.vo;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:24:48
 * <p>
 */
public class Users {

	private Integer userId;

	private String userName;

	private String sex;

	public Users() {

	}
	// get... set.... 略......
}

UserAction.java source to achieve the following:

package com.jsontostruts2.action;

import com.googlecode.jsonplugin.annotations.JSON;
import com.jsontostruts2.vo.Users;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:22:50
 * <p>
 */
@SuppressWarnings("serial")
public class UserAction extends ActionSupport {

	private Users users;

	@JSON(name="USER")
	public Users getUsers() {
		return users;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	@Override
	public String execute() throws Exception {
		users = new Users();
		users.setUserId(1);
		users.setUserName("ctojxzsycztao");
		users.setSex("男人");
		return SUCCESS;
	}

}

Next, we need to configure struts.xml paper is the following in order to write the document will not repeat here I will list the results of the request object and control贴上来together, the content of the document:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<!-- 注意这里扩展不再是 struts-default,而是 json-default -->
	<package name="jsonManager" extends="json-default">
		<!-- 返回结果类型为 json -->
		<action name="userJson">
			<result type="json"/>
		</action>
		<!-- 该action在返回列表时添加进来的 -->
		<action name="jsonlist">
			<result type="json"/>
		</action>

	</package>
</struts>

An ability to create web.xml and userjson.jsp:

web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<filter>
		<filter-name>Struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.FilterDispatcher
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>Struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>Struts2</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

userjson.jsp:

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>json 返回对象处理</title>
	<script language="javascript">
		var xmlHttp = false;
		try{
			xmlHttp = new ActiveXObject("msxml2.XMLHTTP");
		}catch(e1){
			try{
				xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
			}catch(e2){
				try{
					xmlHttp = new XMLHttpRequest();
				}catch(e3){
					xmlHttp = false;
				}
			}
		}
		if(!xmlHttp){
			alert("create xmlHttpRequest fail");
		}
		function jsonResult(){
			xmlHttp.onreadystatechange = function(){
			    if(xmlHttp.readyState == 4) {
				// 将 JSON 对象转换为JSON字符串,需要注意调用eval函数时必须使用"("和")"将JSON字符串括起来,否

则会出错
				var userObj = eval('(' + xmlHttp.responseText + ')');
				var userStr = "<table border=0>";
                    userStr += '<tr><td><b>userId</b></td><td>' + userObj.USER.userId + '</td></tr>';
                    userStr += ('<tr><td><b>userName</b></td><td>' + userObj.USER.userName + '</td></tr>');
                    userStr += ('<tr><td><b>sex</b></td><td>' + userObj.USER.sex + '</td></tr>');
                    userStr += "</table>";
                    document.getElementById('jsonDiv').innerHTML = userStr;
                }
			}
			xmlHttp.open("POST","userJson.action",true);
			xmlHttp.send(null);
		}
	</script>
  </head>
  <body>
  	<div></div>
    <input type="button" value="show">
  </body>
</html>

Now you can release will be applied to your containers which enter http://localhost:8080/struts2ToJson/userjson.jsp Point show, this time you can see the node you want

Fruit, and then return the list to achieve the practice, of course, with the return of objects will be different, we need to convert a List object as a JSON string specification can be sent to the client after the JS,

First of all, the establishment of a specified string into a List of tools, the tool is in an unintentionally brought from the Internet to see spent on, after a little modification, in order to reduce the number of lines of code, I will only paste

Applicable to the sample code:
JsonUtil.java:

package com.jsontostruts2.util;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;

/**
 * <p>
 * @author ChenTao
 * <p>
 * @Date 2009-5-18 下午05:47:27
 * <p>
 */
public class JsonUtil {

	/**
	 * @param object
	 *            任意对象
	 * @return java.lang.String
	 */
	public static String objectToJson(Object object) {
		StringBuilder json = new StringBuilder();
		if (object == null) {
			json.append("\"\"");
		} else if (object instanceof String || object instanceof Integer) {
			json.append("\"").append((String)object).append("\"");
		} else {
			json.append(beanToJson(object));
		}
		return json.toString();
	}

	/**
	 * 功能描述:传入任意一个 javabean 对象生成一个指定规格的字符串
	 * 
	 * @param bean
	 *            bean对象
	 * @return String
	 */
	public static String beanToJson(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = objectToJson(props[i].getName());
					String value = objectToJson(props[i].getReadMethod().invoke(bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * 功能描述:通过传入一个列表对象,调用指定方法将列表中的数据生成一个JSON规格指定字符串
	 * 
	 * @param list
	 *            列表对象
	 * @return java.lang.String
	 */
	public static String listToJson(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(objectToJson(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}
}

UserListAction.java:

package com.jsontostruts2.action;

import java.util.ArrayList;
import java.util.List;

import com.googlecode.jsonplugin.annotations.JSON;
import com.jsontostruts2.util.JsonUtil;
import com.jsontostruts2.vo.Users;
import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * 创 建 人:ChenTao
 * <p>
 * 创建日期:2009-5-18 下午05:45:42
 * <p>
 */
@SuppressWarnings("serial")
public class UserListAction extends ActionSupport {

	/* 用于存放JSON生成后的字符串结果 */
	private String jsonResult;

	@JSON(name="JSONRESULT")
	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		this.jsonResult = jsonResult;
	}

	@Override
	public String execute() throws Exception {
		List<Users> userList = new ArrayList<Users>();
		Users users = new Users();
		users.setUserId(1);
		users.setUserName("ctojxzsycztao");
		users.setSex("男人");
		userList.add(users);
		users = null;
		users = new Users();
		users.setUserId(2);
		users.setUserName("rain");
		users.setSex("女人");
		userList.add(users);
		users = null;
		users = new Users();
		users.setUserId(3);
		users.setUserName("mimi");
		users.setSex("女人");
		userList.add(users);
		jsonResult = JsonUtil.listToJson(userList);
		System.out.println(jsonResult);
		return SUCCESS;
	}
}

Next will be to write a jsonList.JSP the results page for users is

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>json 返回列表处理</title>
	<script language="javascript">
		var xmlHttp = false;
		try{
			xmlHttp = new ActiveXObject("msxml2.XMLHTTP");
		}catch(e1){
			try{
				xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
			}catch(e2){
				try{
					xmlHttp = new XMLHttpRequest();
				}catch(e3){
					xmlHttp = false;
				}
			}
		}
		if(!xmlHttp){
			alert("create xmlHttpRequest fail");
		}
		function jsonListResult(){
			xmlHttp.onreadystatechange = function(){
			    if(xmlHttp.readyState == 4) {
					var userList = eval('(' + xmlHttp.responseText + ')');
					var user = eval(userList.JSONRESULT);
					var result = "<table border=0>";
					result += "<tr><td>userId</td><td>userName</td><td>sex</td></tr>";
					for(var i=0;i<user.length;i++) {
						result += "<tr>";
						result += "<td>"+user[i].userId +"</td>";
						result += "<td>"+user[i].userName+"</td>";
						result += "<td>"+user[i].sex+"</td>";
						result += "</tr>";
					}
					result += "</table>";
                    document.getElementById('jsonDiv').innerHTML = result;
                }
			}
			xmlHttp.open("POST","jsonlist.action",true);
			xmlHttp.send(null);
		}
	</script>
  </head>
  <body>
  	<div></div>
    <input type="button" value="show list">
  </body>
</html>

Will now be deployed to the WEB project repeat containers, start: in the browser, type http://localhost:8080/struts2ToJson/jsonList.jsp Points show list button to see the results of

Is correct, if incorrect please refer to the routines to see if there is no missing part is not configured into the code in the above we have to see @ JSON Notes, the Notes can be changed to return the results of JSON property name, so the wrote the article on here, friends need to download the sample can be downloaded in the annex, which contains the source code of the article and the corresponding JAR