惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
Blog — PlanetScale
Blog — PlanetScale
F
Full Disclosure
云风的 BLOG
云风的 BLOG
U
Unit 42
B
Blog
P
Privacy International News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
NISL@THU
NISL@THU
Recent Announcements
Recent Announcements
The Hacker News
The Hacker News
Engineering at Meta
Engineering at Meta
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
Schneier on Security
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
Webroot Blog
Webroot Blog
Y
Y Combinator Blog
博客园 - 【当耐特】
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
L
Lohrmann on Cybersecurity
Cisco Talos Blog
Cisco Talos Blog
N
News | PayPal Newsroom
Forbes - Security
Forbes - Security
人人都是产品经理
人人都是产品经理
Hacker News: Ask HN
Hacker News: Ask HN
美团技术团队
博客园 - 聂微东
Help Net Security
Help Net Security
A
Arctic Wolf
V
V2EX
The Register - Security
The Register - Security
C
Check Point Blog
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Help Net Security
Google DeepMind News
Google DeepMind News
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
量子位
T
Threat Research - Cisco Blogs

博客园 - leonardleonard

sql去重 分布式云存储系统 Riak CS 开源 转-WCF详解文档最新 .net 基础 HTTP 状态代码 大型网站架构不得不考虑的10个问题 怎么让蜘蛛喜欢你的网站 【Helper】泛型类和集合类的方法 靠垃圾站已经不能继续混下去了 初学做网站的草根站长必读 怎么样让网站有一个好听的中文名称 网站迅速产生外链的方法秘笈 想做成功网站需要注意的几个问题 21世纪开运网www.21kaiyun.com用javascript替换URL中的参数值的技巧 Asp.NET 的Session实现原理 转自21kaiyun.com jquery技巧总结 JavaScript函数 this调用规则 只需九步让你新站成为高权重网站 影响Lucene索引速度原因以及提高索引速度技巧
一些JSON相关的函数 - leonardleonard - 博客园
leonardleona · 2010-07-29 · via 博客园 - leonardleonard

JSON作为一种轻量的数据传输格式,越来越受到人们的青睐。下面是我仿照Prototype的一些实现。

JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,

unfilterJSON:function(json,filter) {

    return json.replace((filter || dom.JSONFilter), function(a,b){

JSONFilter完全抄自Prototype,因为后台基本上只会传输两种格式的东西给我们——文本(xmlhttp.responseText)与XML(xmlhttp.responseXML)。如果要json,我们可以eval一下,或者使用现代浏览器提供的JSON.parse方法。但问题就出在eval中,很容易出现XSS攻击。如果文本是注释就可以避免这问题,在Prototype中还检察一下请求的来源。对于自家的网站的请求,我们完全可以在请求前处理一下,让它变成如下格式:

var text = '/*-secure-\n{"name": "Violet", "occupation": "character", "age": 25}\n*/'

// -> '{"name": "Violet", "occupation": "character", "age": 25}'

到时我们用unfilterJSON函数提取合法的字段来eval就没问题了。

第二个函数,判断字符串是否符合JSON的格式。JSON是有固定的格式,要求键必须被双引号括起来。下面的函数提取自json2

isJSONText:function(json){//

    return /^[\],:{}\s]*$/.test(json.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")

        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")

        .replace(/(?:^|:|,)(?:\s*\[)+/g, ""));

第三个函数,将符合JSON的格式的文本变成JSON对象。第二参数用于指明此文本是否安全(如,是否同源请求)。如果能用原生对象的parse方法就用原生的,否则动态解析它。之所以不用eval,是因为ecma那帮人头脑发热,想禁掉它。

        evalJSON: function( json ,sanitize) {  

            if ( !is(json,"String") || !json )

            json = dom.unfilterJSON(json);

            if ( !sanitize || dom.isJSONText(json) ) {

                return window.JSON && window.JSON.parse ?

                window.JSON.parse( json ) : (new Function("return " + json))();

                throw  "Invalid JSON: " + json;

//http://www.21kaiyun.com

var data =dom.evalJSON( '{ "name": "Violet", "occupation": "character" }');

第四函数,将JSON对象变成文本。

//   var a = [1,2,3,4,{aa:8}]; puts(dom.toJSON(a))

    if (window.JSON && window.JSON.stringify) {

        return JSON.stringify(obj)

    if (typeof window.uneval == 'function') {

    if (typeof obj == 'object') {

        if (dom.is(obj,"Array")) {

            for (var i=0,n=obj.length;i <n;i++) {

                list.push(dom.toJSON(obj[i]));

            return '[' + list.join(',') + ']';

                    list.push('"' + prop + '":' + dom.toJSON(obj[prop]));

            return '{' + list.join(',') + '}';

    } else if (typeof obj == 'string') {

        return '"' + obj.replace(/(["'])/g, '\\$1') + '"';

    if(is(window.JSON,"JSON")){

        return JSON.stringify(obj)

        return n < 10 ? '0' + n : n;

    var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

        return meta[c] ? meta[c] :'\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4);

        return '"' + s.replace(escapable, _char) + '"';

        return  '"' + obj.getUTCFullYear() + '-' +

        f(obj.getUTCMonth() + 1) + '-' +

        f(obj.getUTCDate())      + 'T' +

        f(obj.getUTCHours())     + ':' +

        f(obj.getUTCMinutes())   + ':' +

        f(obj.getUTCSeconds())   + 'Z"' ;

    }else if(is(obj,"Number")){

        return isFinite(obj) ? obj+'' : 'null';

    }else if(is(obj,"Boolean")){

    }else if(is(obj,"String")){

    }else if(is(obj,"Array")){

        return '[' + (dom.filter(obj,function(value){

            return dom.toJSON(value) !== undefined;

    }else if(is(obj,"Object")){

        dom.each(obj,function(value,key){

            value = dom.toJSON(value)

                results.push(dom.toJSON(key) + ': ' + value);

        return '{' + results.join(', ') + '}';

Is函数

目前最精确的判定方法(不包括自定义类型)

        var is = function (obj,type) {

        return (type === "Null" && obj === null) ||

        (type === "Undefined" && obj === void 0 ) ||

        (type === "Number" && isFinite(obj)) ||

         Object.prototype.toString.call(obj).slice(8,-1) === type;

用法如下:

//***************示例一,判定数组与函数

        var forEach = function(array,fn,bind){

          if(is(array,"Array") && is(Array.forEach,"Function")){

            for(var i=0,n=array.length;i<n;i++){

              i in array && fn.call(bind,array[i],i,array)

//***************示例二,判定null

//***************示例二,判定undefined

另一个变种,直接返回表示类型的字符串

var getType = function (obj) {

  var _toString = Object.prototype.toString,undefined;

  return obj === null? "Null":

    obj === undefined ? "Undefined":

    _toString.call(obj).slice(8,-1);

用法:

      alert(getType(arr));//Array

      alert(getType(nil))//Null

      alert(getType(und))//Undefined

      var spans = document.getElementsByTagName("span");

      alert(getType(spans)) //HTMLCollection

      alert(getType(spans[0].childNodes))//NodeList

function isA (thing, canon) {

  // special case for null and undefined

  if (thing == null || canon == null) {

  return Object.getPrototypeOf(Object(thing)) == Object.getPrototypeOf(Object(canon));

function isBool (thing) {

function isNumber (thing) {

  return isA(thing, 0) && isFinite(thing);

function isString (thing) {