Tutorials, Free Online Tutorials, publishbookmarks provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.
Death is not terrible, the terrible thing is that you have not really lived.
relies on jQuery, the following is jQuery.json code:
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} elseif (typeof exports === 'object') {
// CommonJS
factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}
(function($) {
'use strict';
varescape = /["\\\x00-\x1f\x7f-\x9f]/g,
meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
},
hasOwn = Object.prototype.hasOwnProperty;
$.toJSON = typeofJSON === 'object' && JSON.stringify ? JSON.stringify : function(o) {
if (o === null) {
return'null';
}
var pairs, k, name, val,
type = $.type(o);
if (type === 'undefined') {
returnundefined;
}
if (type === 'number' || type === 'boolean') {
returnString(o);
}
if (type === 'string') {
return $.quoteString(o);
}
if (typeof o.toJSON === 'function') {
return $.toJSON(o.toJSON());
}
if (type === 'date') {
var month = o.getUTCMonth() + 1,
day = o.getUTCDate(),
year = o.getUTCFullYear(),
hours = o.getUTCHours(),
minutes = o.getUTCMinutes(),
seconds = o.getUTCSeconds(),
milli = o.getUTCMilliseconds();
if (month < 10) {
month = '0' + month;
}
if (day < 10) {
day = '0' + day;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
if (milli < 100) {
milli = '0' + milli;
}
if (milli < 10) {
milli = '0' + milli;
}
return'"' + year + '-' + month + '-' + day + 'T' +
hours + ':' + minutes + ':' + seconds +
'.' + milli + 'Z"';
}
pairs = [];
if ($.isArray(o)) {
for (k = 0; k < o.length; k++) {
pairs.push($.toJSON(o[k]) || 'null');
}
return'[' + pairs.join(',') + ']';
}
if (typeof o === 'object') {
for (k in o) {
if (hasOwn.call(o, k)) {
type = typeof k;
if (type === 'number') {
name = '"' + k + '"';
} elseif (type === 'string') {
name = $.quoteString(k);
} else {
continue;
}
type = typeof o[k];
if (type !== 'function' && type !== 'undefined') {
val = $.toJSON(o[k]);
pairs.push(name + ':' + val);
}
}
}
return'{' + pairs.join(',') + '}';
}
};
$.evalJSON = typeofJSON === 'object' && JSON.parse ? JSON.parse : function(str) {
/*jshint evil: true */// 1. For the JSON string returned by the server, if the Jquery asynchronous request does not make a type, or accept it in a string,// So you need to do an objectized treatment, the method is either too troublesome, or the string is executed once in the eval ().// This method is also suitable for obtaining JSON objects in ordinary JavaScipt. The following example is:// Convert to JSON objectreturneval('(' + str + ')');
};
$.secureEvalJSON = typeofJSON === 'object' && JSON.parse ? JSON.parse : function(str) {
var filtered =
str
.replace(/\\["\\\/bfnrtu]/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
if (/^[\],:{}\s]*$/.test(filtered)) {
/*jshint evil: true */returneval('(' + str + ')');
}
thrownewSyntaxError('Error parsing JSON, source is not valid.');
};
$.quoteString = function(str) {
if (str.match(escape)) {
return'"' + str.replace(escape, function(a) {
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return'\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return'"' + str + '"';
};
}));
jsonDemo.aspx:
<!DOCTYPE html><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title><scriptsrc="js/jquery-1.10.2-min.js"type="text/javascript"></script><scriptsrc="js/jquery.json.js"type="text/javascript"></script><scripttype="text/javascript">
$(function() {
var obj = newObject();
obj.name = "Zhang San";
obj.age = "12";
obj.job = "php";
// Convert to json stringvar strjson = $.toJSON(obj);
$(".strjson").text(strjson);
});
</script><scripttype="text/javascript">var thing = { plugin: 'jquery-json', version: 2.3 };
// Convert to json stringvar encoded = $.toJSON(thing);
// '{"plugin":"jquery-json","version":2.3}'// The reason is: Eval itself. Since JSON starts and ends in the way of "{}", in JS, it will be treated as a statement block, so it must be mandatory to convert it into an expression.// The purpose of adding brackets is to force the EVAL function to force the expression in parentheses into objects when processing the JavaScript code, instead of being executed as a statement.// Take an example, for example, the object of the object is {}. If the brackets of the outer layer are not added, then EVAL will identify the bracket as the start and end of the JavaScript code block, then {} will be considered to be executed A sentence empty sentence.// So the following two execution results are different://alert(eval("{}"); // return undefined//alert(eval("({})");// return object[Object]// For this writing, you can see everywhere in JS.//, such as: (function ()) {} (); when doing closure operation, etc.var name = $.evalJSON(encoded).plugin;
// "jquery-json"var version = $.evalJSON(encoded).version;
</script><scripttype="text/javascript">// The second analysis method is to complete the use of the Function object. Its typical application is to analyze the data data analysis under the AJAX method in jqueryvar json='{"name":"CJ","age":18}';
data =(newFunction("","return "+json))();
// At this time, the data is a JSON object that will be parsed into a JSON objectvar dataStr="{root: " +
"[{name:'1',value:'0'}," +
"{name: '6101', value: 'Beijing'}," +
"{name: '6102', value: 'Tianjin City'}," +
"{name: '6103', value: 'Shanghai'}," +
"{name: '6104', value: 'Chongqing City'}," +
"{name: '6105', value: 'Weinan City'}," +
"{name: '6106', value: 'Yan'an City'}," +
"{name: '6107', value: 'Hanzhong City'}," +
"{name: '6108', value: 'Yulin City'}," +
"{name: '6109', value: 'Ankang City'}," +
"{name: '6110', value: 'Shangluo City'}]}";
var dataObj=eval("("+dataStr+")");// Convert to JSON object
$.each(dataObj.root, function(idx, item) {
if (idx == 0) {
returntrue;
}
// Output the name and value of each root sub -object//$(".Totalstr").append("name:" + item.name + ",value:" + item.value);
});
</script><scripttype="text/javascript">// String represents, intelligent transition quotesvar myquoteString = $.quoteString('"Where are we going?", Children ask .we laughed and kept saying "see u soon", but inside we both knew we \' d never see each Other Again. We laughed and said goodbye to goodbye Far forever. ')
alert(myquoteString);
</script></head><body><formid="form1"runat="server"><div>json string:<spanclass="strjson"></span></div><hr /></form></body></html>