json.js

由于json官网被强,现保存源码一份以备不时之需,直接保存成js文件即可。

  1 /*
  2     json.js
  3     2007-08-05
  4
  5     Public Domain
  6
  7     This file adds these methods to JavaScript:
  8
  9         array.toJSONString()
 10         boolean.toJSONString()
 11         date.toJSONString()
 12         number.toJSONString()
 13         object.toJSONString()
 14         string.toJSONString()
 15             These methods produce a JSON text from a JavaScript value.
 16             It must not contain any cyclical references. Illegal values
 17             will be excluded.
 18
 19             The default conversion for dates is to an ISO string. You can
 20             add a toJSONString method to any date object to get a different
 21             representation.
 22
 23         string.parseJSON(filter)
 24             This method parses a JSON text to produce an object or
 25             array. It can throw a SyntaxError exception.
 26
 27             The optional filter parameter is a function which can filter and
 28             transform the results. It receives each of the keys and values, and
 29             its return value is used instead of the original value. If it
 30             returns what it received, then structure is not modified. If it
 31             returns undefined then the member is deleted.
 32
 33             Example:
 34
 35             // Parse the text. If a key contains the string ‘date‘ then
 36             // convert the value to a date.
 37
 38             myData = text.parseJSON(function (key, value) {
 39                 return key.indexOf(‘date‘) >= 0 ? new Date(value) : value;
 40             });
 41
 42     It is expected that these methods will formally become part of the
 43     JavaScript Programming Language in the Fourth Edition of the
 44     ECMAScript standard in 2008.
 45
 46     This file will break programs with improper for..in loops. See
 47     http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
 48
 49     This is a reference implementation. You are free to copy, modify, or
 50     redistribute.
 51
 52     Use your own copy. It is extremely unwise to load untrusted third party
 53     code into your pages.
 54 */
 55
 56 /*jslint evil: true */
 57
 58 // Augment the basic prototypes if they have not already been augmented.
 59
 60 if (!Object.prototype.toJSONString) {
 61
 62     Array.prototype.toJSONString = function () {
 63         var a = [],     // The array holding the partial texts.
 64             i,          // Loop counter.
 65             l = this.length,
 66             v;          // The value to be stringified.
 67
 68
 69 // For each value in this array...
 70
 71         for (i = 0; i < l; i += 1) {
 72             v = this[i];
 73             switch (typeof v) {
 74             case ‘object‘:
 75
 76 // Serialize a JavaScript object value. Ignore objects thats lack the
 77 // toJSONString method. Due to a specification error in ECMAScript,
 78 // typeof null is ‘object‘, so watch out for that case.
 79
 80                 if (v) {
 81                     if (typeof v.toJSONString === ‘function‘) {
 82                         a.push(v.toJSONString());
 83                     }
 84                 } else {
 85                     a.push(‘null‘);
 86                 }
 87                 break;
 88
 89             case ‘string‘:
 90             case ‘number‘:
 91             case ‘boolean‘:
 92                 a.push(v.toJSONString());
 93
 94 // Values without a JSON representation are ignored.
 95
 96             }
 97         }
 98
 99 // Join all of the member texts together and wrap them in brackets.
100
101         return ‘[‘ + a.join(‘,‘) + ‘]‘;
102     };
103
104
105     Boolean.prototype.toJSONString = function () {
106         return String(this);
107     };
108
109
110     Date.prototype.toJSONString = function () {
111
112 // Eventually, this method will be based on the date.toISOString method.
113
114         function f(n) {
115
116 // Format integers to have at least two digits.
117
118             return n < 10 ? ‘0‘ + n : n;
119         }
120
121         return ‘"‘ + this.getUTCFullYear() + ‘-‘ +
122                 f(this.getUTCMonth() + 1) + ‘-‘ +
123                 f(this.getUTCDate()) + ‘T‘ +
124                 f(this.getUTCHours()) + ‘:‘ +
125                 f(this.getUTCMinutes()) + ‘:‘ +
126                 f(this.getUTCSeconds()) + ‘Z"‘;
127     };
128
129
130     Number.prototype.toJSONString = function () {
131
132 // JSON numbers must be finite. Encode non-finite numbers as null.
133
134         return isFinite(this) ? String(this) : ‘null‘;
135     };
136
137
138     Object.prototype.toJSONString = function () {
139         var a = [],     // The array holding the partial texts.
140             k,          // The current key.
141             v;          // The current value.
142
143 // Iterate through all of the keys in the object, ignoring the proto chain
144 // and keys that are not strings.
145
146         for (k in this) {
147             if (typeof k === ‘string‘ &&
148                     Object.prototype.hasOwnProperty.apply(this, [k])) {
149                 v = this[k];
150                 switch (typeof v) {
151                  case ‘object‘: if (v == this) continue;
152 // Serialize a JavaScript object value. Ignore objects that lack the
153 // toJSONString method. Due to a specification error in ECMAScript,
154 // typeof null is ‘object‘, so watch out for that case.
155
156                     if (v) {
157                         if (typeof v.toJSONString === ‘function‘) {
158                             a.push(k.toJSONString() + ‘:‘ + v.toJSONString());
159                         }
160                     } else {
161                         a.push(k.toJSONString() + ‘:null‘);
162                     }
163                     break;
164
165                 case ‘string‘:
166                 case ‘number‘:
167                 case ‘boolean‘:
168                     a.push(k.toJSONString() + ‘:‘ + v.toJSONString());
169
170 // Values without a JSON representation are ignored.
171
172                 }
173             }
174         }
175
176 // Join all of the member texts together and wrap them in braces.
177
178         return ‘{‘ + a.join(‘,‘) + ‘}‘;
179     };
180
181
182     (function (s) {
183
184 // Augment String.prototype. We do this in an immediate anonymous function to
185 // avoid defining global variables.
186
187 // m is a table of character substitutions.
188
189         var m = {
190             ‘\b‘: ‘\\b‘,
191             ‘\t‘: ‘\\t‘,
192             ‘\n‘: ‘\\n‘,
193             ‘\f‘: ‘\\f‘,
194             ‘\r‘: ‘\\r‘,
195             ‘"‘ : ‘\\"‘,
196             ‘\\‘: ‘\\\\‘
197         };
198
199
200         s.parseJSON = function (filter) {
201             var j;
202
203             function walk(k, v) {
204                 var i;
205                 if (v && typeof v === ‘object‘) {
206                     for (i in v) {
207                         if (Object.prototype.hasOwnProperty.apply(v, [i])) {
208                             v[i] = walk(i, v[i]);
209                         }
210                     }
211                 }
212                 return filter(k, v);
213             }
214
215
216 // Parsing happens in three stages. In the first stage, we run the text against
217 // a regular expression which looks for non-JSON characters. We are especially
218 // concerned with ‘()‘ and ‘new‘ because they can cause invocation, and ‘=‘
219 // because it can cause mutation. But just to be safe, we will reject all
220 // unexpected characters.
221
222 // We split the first stage into 3 regexp operations in order to work around
223 // crippling deficiencies in Safari‘s regexp engine. First we replace all
224 // backslash pairs with ‘@‘ (a non-JSON character). Second we delete all of
225 // the string literals. Third, we look to see if only JSON characters
226 // remain. If so, then the text is safe for eval.
227
228             if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(this.
229                     replace(/\\./g, ‘@‘).
230                     replace(/"[^"\\\n\r]*"/g, ‘‘))) {
231
232 // In the second stage we use the eval function to compile the text into a
233 // JavaScript structure. The ‘{‘ operator is subject to a syntactic ambiguity
234 // in JavaScript: it can begin a block or an object literal. We wrap the text
235 // in parens to eliminate the ambiguity.
236
237                 j = eval(‘(‘ + this + ‘)‘);
238
239 // In the optional third stage, we recursively walk the new structure, passing
240 // each name/value pair to a filter function for possible transformation.
241
242                 return typeof filter === ‘function‘ ? walk(‘‘, j) : j;
243             }
244
245 // If the text is not JSON parseable, then a SyntaxError is thrown.
246
247             throw new SyntaxError(‘parseJSON‘);
248         };
249
250
251         s.toJSONString = function () {
252
253 // If the string contains no control characters, no quote characters, and no
254 // backslash characters, then we can simply slap some quotes around it.
255 // Otherwise we must also replace the offending characters with safe
256 // sequences.
257
258             if (/["\\\x00-\x1f]/.test(this)) {
259                 return ‘"‘ + this.replace(/[\x00-\x1f\\"]/g, function (a) {
260                     var c = m[a];
261                     if (c) {
262                         return c;
263                     }
264                     c = a.charCodeAt();
265                     return ‘\\u00‘ +
266                         Math.floor(c / 16).toString(16) +
267                         (c % 16).toString(16);
268                 }) + ‘"‘;
269             }
270             return ‘"‘ + this + ‘"‘;
271         };
272     })(String.prototype);
273 }
时间: 2024-08-06 07:27:10

json.js的相关文章

在JavaScript中使用json.js:Ajax项目之GET请求(同步)

1.用php编写一个提供数据的响应程序(phpdata.php) <?php $arr=array(1,2,3,4); //将数组编码为JSON格式的数据 $jsonarr=json_encode($arr); //输出JSON格式的数据 echo $jsonarr; ?> 2.客户端(ajax.html) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w

在JavaScript中使用json.js:访问JSON编码的某个值

演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/jav

java对象转JSON JS取JSON数据

JsonConfig config = new JsonConfig(); config.setJsonPropertyFilter(new PropertyFilter() { @Override public boolean apply(Object arg0, String arg1, Object arg2) { // 过滤掉对象里的包含自己的属性(自己关联自己) if (arg1.equals("wareTypes") || arg1.equals("skillS&

在JavaScript中使用json.js:使得js数组转为JSON编码

在json的官网中下载json.js,然后在script中引入,以使用json.js提供的两个关键方法. 1.数组对象.toJSONString() 这个方法将返回一个JSON编码格式的字符串,用来表示类型中的数据. 演示: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"

用json2.js 代替 json.js防止与jQuery的js冲突

1 s.toJSONString json.js:259 2 Object.toJSONString json.js:158 3 Uncaught RangeError: Maximum call stack size exceeded 附 json2.js下载地址

在JavaScript中使用json.js:Ajax项目之POST请求(异步)

经常在百度搜索框输入一部分关键词后,弹出候选关键热词.现在我们就用Ajax技术来实现这一功能. 一.下载json.js文件 百度搜一下,最好到json官网下载,安全起见. 并与新建的两个文件部署如图 json.js也可直接复制此处的代码获取. 1 /* 2 json.js 3 2008-03-14 4 5 Public Domain 6 7 No warranty expressed or implied. Use at your own risk. 8 9 This file has been

json (js对象标记)

基础 JSON: JavaScript Object Notation (JavaScript对象表示法) 网络媒体类型是 application/json,文件名扩展是 .json JSON 独立于语言和平台,是轻量级的文本数据交换格式 JSON 语法是 JavaScript 语法的子集. JSON有2种结构:无序的对象结构,有序的数组结构 JSON转换 var jsonObject = eval('('+jsonText+')'); var newJsonText = people.toJS

json js 算法 面试

Git远程操作详解 - 阮一峰的网络日志http://www.ruanyifeng.com/blog/2014/06/git_remote.html 2.XHR_百度文库http://wenku.baidu.com/link?url=bxf_ou2tKCmrl4OW_zKrH8Oikgtrjn8nuvLE32wWR-v8B946Gl26C6QoaZKBXme869Do-h44DfzTBcvQxqTn_jtM0IXWFBXEQdHt4dYMIhq Java web过滤器验证登录(避免未经登录进入主

ajax和json js数据类型和操作

字符串(String).数字(Number NAN字符串转换数字失败).布尔(Boolean).数组(Array).对象(Object).空(Null).未定义(Undefined). <form> <input type="text" id="user"> <input type="password" id="pwd"> </form> <input type="