JSON 教程
- 第1节:JSON 简介
- 第2节:JSON 语法
- 第3节:JSON 使用
- 第4节:JSONP 教程
- 第5节:JSON 数据类型
- 第6节:JSON 对象
- 第7节:JSON 模式
- 第8节:JSON 与 XML 对比
- 第9节:JSON 基础结构
- 第10节:JSON 数据格式
- 第11节:JSON 数据解析的方法
- 第12节:JSON 数据解析过程详解
- 第13节:JSON 解析URL参数
- 第14节:JSON 元素的添加删除
- 第15节:JSON 数据解析的3种方式
- 第16节:JavaScript 解析Json字符串的性能比较分析代码
- 第17节:JavaScript解析json格式数据简单示例
- 第18节:JSON数据遍历之for-in
- 第19节:jQuery 遍历Json的实现代码
- 第20节:JS遍历Json字符串
- 第21节:直接在JS里创建JSON数据然后遍历使用
- 第22节:JS循环遍历JSON数据的方法
- 第23节:js 遍历json返回的map内容示例代码
- 第24节:JSP+jquery使用ajax方式调用json的实现方法
- 第25节:jquery中的ajax方法怎样通过JSONP进行远程调用
- 第26节:jquery ajax jsonp跨域调用实例代码
- 第27节:jQuery插件jQuery-JSONP开发ajax调用使用注意事项
- 第28节:json的键名为数字时的调用方式
- 第29节:php跨域调用json的例子
- 第30节:jquery中ajax调用json数据的使用说明
- 第31节:ASP.NET(AJAX+JSON)实现对象调用
- 第32节:JavaScript转换与解析JSON方法实例详解
- 第33节:将JavaScript的jQuery库中表单转化为JSON对象的方法
- 第34节:javascript中JSON对象与JSON字符串相互转换实例
- 第35节:JavaScript中字符串(string)转json的方法
- 第36节:JavaScript将XML转成JSON的方法
- 第37节:java与javascript之间json格式数据互转介绍
- 第38节:转义字符(\)对JavaScript中JSON.parse的影响概述
- 第39节:JavaScript中json对象和string对象之间相互转化
- 第40节:javascript中将Object转换为String函数代码 (json str)
- 第41节:转换json格式的日期为Javascript对象的函数
- 第42节:AJAX跨域请求获取JSON数据
- 第43节:JS根据key值获取URL中的参数值
- 第44节:jquery用ajax方式从后台获取json数据后如何将内容填充到下拉列表
- 第45节:js获取json元素数量的方法
- 第46节:JSONP获取Twitter和Facebook文章数的具体步骤
- 第47节:js获取通过ajax返回的map型的JSONArray的方法
- 第48节:JSP中获取ExtJS.Ajax前台传递的JSON数据实现过程
- 第49节:jQuery中使用Ajax获取JSON格式数据示例代码
- 第50节:JQuery 获取json数据$.getJSON方法的实例代码
- 第51节:javascript中JSON对象与JSON字符串相互转换实例
- 第52节:JavaScript中字符串(string)转json的方法
- 第53节:IE6/IE7中JavaScript json提示缺少标识符、字符串或数字问题处理
- 第54节:使用JavaScript构建JSON格式字符串实现步骤
- 第55节:JavaScript 解析Json字符串的性能比较分析代码
- 第56节:javascript巧用eval函数组装表单输入项为json对象的方法
- 第57节:用javascript对一个json数组深度赋值示例
- 第58节:解析javascript 数组(以及json元素的添加删除)
- 第59节:js数组如何添加json数据
- 第60节:js/jquery解析json和数组格式的方法详解
JavaScript 解析Json字符串的性能比较分析代码
我们在使用AJAX来做服务器端和客户端交互的时候,一般的做法是让服务器端返回一段JSON字符串,然后在客户端把它解析成JavaScript对象。
解析时用到的方法一般是eval或者new function,而目前IE8和Firefox3.1又内置了原生的JSON对象(据说会有一定的性能提升)。那我们在实际使用的时候怎样从这三种方法(因为性能问题,不考虑用javascript实现的解析)里面来选择呢?面对众多的浏览器,哪种方式的性能是最好的呢?
一、测试方法
1、首先指定测试次数及JSON字符串
代码如下:
var count = 10000,
o = null,
i = 0,
jsonString = '{"value":{"items": [{"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}';
2、循环解析并记录时间
eval 解析
代码如下:
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = eval( "(" + jsonString + ")" );
}
Console.output( "eval:" + ( new Date() - beginTime ) );
new Function 函数解析
代码如下:
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = new Function( "return " + jsonString )();
}
Console.output( "new Function:" + ( new Date() - beginTime ) );
native 原生解析
代码如下:
if ( typeof JSON !== "undefined" ) {
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString ); }
Console.output( "native:" + ( new Date() - beginTime ) );
} else {
Console.output( "native:not support!" );
}
二、测试对象
选择目前主流的浏览器(不考虑Maxthon一类的外壳),包括IE6、7、8,Firefox2、3、3.1,Chrome,Opera及Safari3、4。三、测试环境
T9300 CPU + 4G RAM + Windows2003,其中IE8使用的是Vista的环境,IE7在另外一台工作机(2G CPU + 2G RAM + Windows2003),考虑到主要是测试浏览器客户端的性能,结果的误差应该能够接受。注释:
*数值越小越好
*在当前列中绿色背景的表示性能最好,红色性能最差
*在当前列中绿色背景的表示性能最好,红色性能最差
1、Firefox2、3全部垫底,IE6的性能优于IE7(可能和机器不一致有关),Chrome和Safari4的性能远远超出其它浏览器。
2、不同的浏览器下eval和new Function的性能不一致,总的来说eval更好,但Firefox下new Function的性能是eval的一倍,为了更好的兼容各个浏览器,我们把对JSON的解析单独封装成一个对象来处理:
wrapper
代码如下:
var __json = null;
if (typeof JSON !== "undefined") {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function(text) {
if (__json !== null) {
return __json.parse(text);
}
if (browser.gecko) {
return new Function("return " + text)();
}
return eval("(" + text + ")")
}
};
var beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse(jsonString);
}
Console.output("wrapper:" + (new Date() - beginTime));
由于涉及到调用对象的开销,封装后JSON对象会比单独调用更慢,但它能保证在各个浏览器下使用最适合的方法。
五、结论
解析Json字符串时,不同的浏览器选择不同的方法:- IE6、7使用eval
- IE8使用原生的JSON对象
- Firefox2、3使用new Function
- Safari4使用eval
- 其它浏览器下eval和new Function的性能基本一致
2009.03.23:屏蔽所有Firefox的Add-Ons再进行测试
由于Known在Firefox下运行代码得到了完全不一致的结果,怀疑是Firefox的插件导致,于是禁掉所有插件后(后来表明几乎由Firebug导致),重新在Firefox2、3下测试了一下,结果如下:
这表明Firefox本身的性能并不是象我们先前测试的那样低,在去掉插件后性能还是很不错。但是没有Firebug一类的插件支持,Firefox对我们的吸引力也大大降低了。
2009.03.31:循环中每次使用新的json字符串
根据Oliver的描述,他猜测是由于Safari4和Chrome缓存了eval的结果从而导致它们的测试成绩“虚”高,测试结果证明了他的推测:
附:全部代码
2009.03.31:循环中每次使用新的json字符串
根据Oliver的描述,他猜测是由于Safari4和Chrome缓存了eval的结果从而导致它们的测试成绩“虚”高,测试结果证明了他的推测:
从这个结果中我们可以看到,Opera的性能最好,Ie8其次。
主要修改的代码:
代码如下:
//eval 2: var beginTime = new Date();
for (i = 0; i < count; i++) {
o = eval("(" + '{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}' + ")");
}
Console.output("eval:" + (new Date() - beginTime));
//new Function
beginTime = new Date();
for (i = 0; i < count; i++) {
o = new Function("return " + '{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}')();
}
Console.output("new Function:" + (new Date() - beginTime));
//native
if (typeof JSON !== "undefined") {
beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse('{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}');
}
Console.output("native:" + (new Date() - beginTime));
} else {
Console.output("native:not support!");
}
//wrapper
var __json = null;
if (typeof JSON !== "undefined") {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function(text) {
if (__json !== null) {
return __json.parse(text);
}
if (browser.gecko) {
return new Function("return " + text)();
}
return eval("(" + text + ")")
}
};
beginTime = new Date();
for (i = 0; i < count; i++) {
o = JSON.parse('{"value":{"items": [{"x":' + i + ',"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}');
}
Console.output("wrapper:" + (new Date() - beginTime));
代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Parse JsonString</title>
</head>
<body>
<div id="consoleRegion"></div>
<script type="text/javascript">
//yui
var Browser = function() {
var o = {
ie: 0,
opera: 0,
gecko: 0,
webkit: 0
};
var ua = navigator.userAgent, m;
if ( ( /KHTML/ ).test( ua ) ) {
o.webkit = 1;
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m&&m[1]) {
o.webkit=parseFloat(m[1]);
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
m=ua.match(/Opera[\s\/]([^\s]*)/);
if (m&&m[1]) {
o.opera=parseFloat(m[1]);
} else { // not opera or webkit
m=ua.match(/MSIE\s([^;]*)/);
if (m&&m[1]) {
o.ie=parseFloat(m[1]);
} else { // not opera, webkit, or ie
m=ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko=1; // Gecko detected, look for revision
m=ua.match(/rv:([^\s\)]*)/);
if (m&&m[1]) {
o.gecko=parseFloat(m[1]);
}
}
}
}
}
return o;
}();
var Console = {
consoleRegion: null,
getRegion: function() {
if ( this.consoleRegion === null ) {
this.consoleRegion = document.getElementById( "consoleRegion" );
}
return this.consoleRegion;
},
output: function( text ) {
this.getRegion().innerHTML += "<br/>" + text;
}
};
//test code
var count = 10000, o = null, i = 0, jsonString = '{"value":{"items": [{"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}, {"x":1,"y":2,"z":3}]},"error":null}';
//eval
var beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = eval( "(" + jsonString + ")" );
}
Console.output( "eval:" + ( new Date() - beginTime ) );
//new Function
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = new Function( "return " + jsonString )();
}
Console.output( "new Function:" + ( new Date() - beginTime ) );
//native
if ( typeof JSON !== "undefined" ) {
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString );
}
Console.output( "native:" + ( new Date() - beginTime ) );
} else {
Console.output( "native:not support!" );
}
//wrapper
var __json = null;
if ( typeof JSON !== "undefined" ) {
__json = JSON;
}
var browser = Browser;
var JSON = {
parse: function( text ) {
if ( __json !== null ) {
return __json.parse( text );
}
if ( browser.gecko ) {
return new Function( "return " + text )();
}
return eval( "(" + text + ")" )
}
};
beginTime = new Date();
for ( i = 0; i < count; i++ ) {
o = JSON.parse( jsonString );
}
Console.output( "wrapper:" + ( new Date() - beginTime ) );
//alert( o.value.items[0].z );
</script>
</body>
</html>
JavaScript解析json字符串代码:
代码一 一个 Servlet
[java] view plain copy 在CODE上查看代码片派生到我的代码片
[java] view plain copy 在CODE上查看代码片派生到我的代码片
package com.ghj.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = -699926309344319475L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");
PrintWriter out = response.getWriter();
Map<String, List<String>> dataMap = new HashMap<String, List<String>>();
List<String > gradeList = new ArrayList<String>();//年级
gradeList.add("初中一年级");
gradeList.add("初中二年级");
gradeList.add("初中三年级");
dataMap.put("gradeList", gradeList);
List<String> courseList = new ArrayList<String>();//课程
courseList.add("语文");
courseList.add("数学");
courseList.add("物理");
dataMap.put("courseList", courseList);
out.write(new Gson().toJson(dataMap));
out.flush();
out.close();
}
}
说明:这里使用了gson-2.2.2.jar包代码二 一个jsp
[html] view plain copy 在CODE上查看代码片派生到我的代码片
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>首页</title>
<script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$("#json").click(function(){
$.ajax({
type: "POST",
url: "<%=basePath%>JsonServlet",
success: function(data){
var grades = data.gradeList;
for(var index in grades){//年级
console.log(grades[index]);
}
var courses = data.courseList;
for(var index in courses){//课程
console.log(courses[index]);
}
},
error:function(){
alert("数据请求失败!");
}
});
});
});
</script>
</head>
<body>
<button id="json">JavaScript解析JSON字符串</button>
</body>
</html>