1. 字符串转对象(strJSON代表json字符串)
  2. var obj = eval(strJSON);
  3. var obj = strJSON.parseJSON();
  4. var obj = JSON.parse(strJSON);
  5. json对象转字符串(obj代表json对象)
  6. var str = obj.toJSONString();
  7. var str = JSON.stringify(obj)
  8. 运用时候需要除了eval()以外需要json2.js包(切记哦)

json2.js

  1. /*
  2. json2.js
  3. 2015-05-03
  4.  
  5. Public Domain.
  6.  
  7. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  8.  
  9. See http://www.JSON.org/js.html
  10.  
  11. This code should be minified before deployment.
  12. See http://javascript.crockford.com/jsmin.html
  13.  
  14. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  15. NOT CONTROL.
  16.  
  17. This file creates a global JSON object containing two methods: stringify
  18. and parse. This file is provides the ES5 JSON capability to ES3 systems.
  19. If a project might run on IE8 or earlier, then this file should be included.
  20. This file does nothing on ES5 systems.
  21.  
  22. JSON.stringify(value, replacer, space)
  23. value any JavaScript value, usually an object or array.
  24.  
  25. replacer an optional parameter that determines how object
  26. values are stringified for objects. It can be a
  27. function or an array of strings.
  28.  
  29. space an optional parameter that specifies the indentation
  30. of nested structures. If it is omitted, the text will
  31. be packed without extra whitespace. If it is a number,
  32. it will specify the number of spaces to indent at each
  33. level. If it is a string (such as '\t' or ' '),
  34. it contains the characters used to indent at each level.
  35.  
  36. This method produces a JSON text from a JavaScript value.
  37.  
  38. When an object value is found, if the object contains a toJSON
  39. method, its toJSON method will be called and the result will be
  40. stringified. A toJSON method does not serialize: it returns the
  41. value represented by the name/value pair that should be serialized,
  42. or undefined if nothing should be serialized. The toJSON method
  43. will be passed the key associated with the value, and this will be
  44. bound to the value
  45.  
  46. For example, this would serialize Dates as ISO strings.
  47.  
  48. Date.prototype.toJSON = function (key) {
  49. function f(n) {
  50. // Format integers to have at least two digits.
  51. return n < 10
  52. ? '0' + n
  53. : n;
  54. }
  55.  
  56. return this.getUTCFullYear() + '-' +
  57. f(this.getUTCMonth() + 1) + '-' +
  58. f(this.getUTCDate()) + 'T' +
  59. f(this.getUTCHours()) + ':' +
  60. f(this.getUTCMinutes()) + ':' +
  61. f(this.getUTCSeconds()) + 'Z';
  62. };
  63.  
  64. You can provide an optional replacer method. It will be passed the
  65. key and value of each member, with this bound to the containing
  66. object. The value that is returned from your method will be
  67. serialized. If your method returns undefined, then the member will
  68. be excluded from the serialization.
  69.  
  70. If the replacer parameter is an array of strings, then it will be
  71. used to select the members to be serialized. It filters the results
  72. such that only members with keys listed in the replacer array are
  73. stringified.
  74.  
  75. Values that do not have JSON representations, such as undefined or
  76. functions, will not be serialized. Such values in objects will be
  77. dropped; in arrays they will be replaced with null. You can use
  78. a replacer function to replace those with JSON values.
  79. JSON.stringify(undefined) returns undefined.
  80.  
  81. The optional space parameter produces a stringification of the
  82. value that is filled with line breaks and indentation to make it
  83. easier to read.
  84.  
  85. If the space parameter is a non-empty string, then that string will
  86. be used for indentation. If the space parameter is a number, then
  87. the indentation will be that many spaces.
  88.  
  89. Example:
  90.  
  91. text = JSON.stringify(['e', {pluribus: 'unum'}]);
  92. // text is '["e",{"pluribus":"unum"}]'
  93.  
  94. text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  95. // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  96.  
  97. text = JSON.stringify([new Date()], function (key, value) {
  98. return this[key] instanceof Date
  99. ? 'Date(' + this[key] + ')'
  100. : value;
  101. });
  102. // text is '["Date(---current time---)"]'
  103.  
  104. JSON.parse(text, reviver)
  105. This method parses a JSON text to produce an object or array.
  106. It can throw a SyntaxError exception.
  107.  
  108. The optional reviver parameter is a function that can filter and
  109. transform the results. It receives each of the keys and values,
  110. and its return value is used instead of the original value.
  111. If it returns what it received, then the structure is not modified.
  112. If it returns undefined then the member is deleted.
  113.  
  114. Example:
  115.  
  116. // Parse the text. Values that look like ISO date strings will
  117. // be converted to Date objects.
  118.  
  119. myData = JSON.parse(text, function (key, value) {
  120. var a;
  121. if (typeof value === 'string') {
  122. a =
  123. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  124. if (a) {
  125. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  126. +a[5], +a[6]));
  127. }
  128. }
  129. return value;
  130. });
  131.  
  132. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  133. var d;
  134. if (typeof value === 'string' &&
  135. value.slice(0, 5) === 'Date(' &&
  136. value.slice(-1) === ')') {
  137. d = new Date(value.slice(5, -1));
  138. if (d) {
  139. return d;
  140. }
  141. }
  142. return value;
  143. });
  144.  
  145. This is a reference implementation. You are free to copy, modify, or
  146. redistribute.
  147. */
  148.  
  149. /*jslint
  150. eval, for, this
  151. */
  152.  
  153. /*property
  154. JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  155. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  156. lastIndex, length, parse, prototype, push, replace, slice, stringify,
  157. test, toJSON, toString, valueOf
  158. */
  159.  
  160. // Create a JSON object only if one does not already exist. We create the
  161. // methods in a closure to avoid creating global variables.
  162.  
  163. if (typeof JSON !== 'object') {
  164. JSON = {};
  165. }
  166.  
  167. (function () {
  168. 'use strict';
  169.  
  170. var rx_one = /^[\],:{}\s]*$/,
  171. rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
  172. rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
  173. rx_four = /(?:^|:|,)(?:\s*\[)+/g,
  174. rx_escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  175. rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  176.  
  177. function f(n) {
  178. // Format integers to have at least two digits.
  179. return n < 10
  180. ? '0' + n
  181. : n;
  182. }
  183.  
  184. function this_value() {
  185. return this.valueOf();
  186. }
  187.  
  188. if (typeof Date.prototype.toJSON !== 'function') {
  189.  
  190. Date.prototype.toJSON = function () {
  191.  
  192. return isFinite(this.valueOf())
  193. ? this.getUTCFullYear() + '-' +
  194. f(this.getUTCMonth() + 1) + '-' +
  195. f(this.getUTCDate()) + 'T' +
  196. f(this.getUTCHours()) + ':' +
  197. f(this.getUTCMinutes()) + ':' +
  198. f(this.getUTCSeconds()) + 'Z'
  199. : null;
  200. };
  201.  
  202. Boolean.prototype.toJSON = this_value;
  203. Number.prototype.toJSON = this_value;
  204. String.prototype.toJSON = this_value;
  205. }
  206.  
  207. var gap,
  208. indent,
  209. meta,
  210. rep;
  211.  
  212. function quote(string) {
  213.  
  214. // If the string contains no control characters, no quote characters, and no
  215. // backslash characters, then we can safely slap some quotes around it.
  216. // Otherwise we must also replace the offending characters with safe escape
  217. // sequences.
  218.  
  219. rx_escapable.lastIndex = 0;
  220. return rx_escapable.test(string)
  221. ? '"' + string.replace(rx_escapable, function (a) {
  222. var c = meta[a];
  223. return typeof c === 'string'
  224. ? c
  225. : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  226. }) + '"'
  227. : '"' + string + '"';
  228. }
  229.  
  230. function str(key, holder) {
  231.  
  232. // Produce a string from holder[key].
  233.  
  234. var i, // The loop counter.
  235. k, // The member key.
  236. v, // The member value.
  237. length,
  238. mind = gap,
  239. partial,
  240. value = holder[key];
  241.  
  242. // If the value has a toJSON method, call it to obtain a replacement value.
  243.  
  244. if (value && typeof value === 'object' &&
  245. typeof value.toJSON === 'function') {
  246. value = value.toJSON(key);
  247. }
  248.  
  249. // If we were called with a replacer function, then call the replacer to
  250. // obtain a replacement value.
  251.  
  252. if (typeof rep === 'function') {
  253. value = rep.call(holder, key, value);
  254. }
  255.  
  256. // What happens next depends on the value's type.
  257.  
  258. switch (typeof value) {
  259. case 'string':
  260. return quote(value);
  261.  
  262. case 'number':
  263.  
  264. // JSON numbers must be finite. Encode non-finite numbers as null.
  265.  
  266. return isFinite(value)
  267. ? String(value)
  268. : 'null';
  269.  
  270. case 'boolean':
  271. case 'null':
  272.  
  273. // If the value is a boolean or null, convert it to a string. Note:
  274. // typeof null does not produce 'null'. The case is included here in
  275. // the remote chance that this gets fixed someday.
  276.  
  277. return String(value);
  278.  
  279. // If the type is 'object', we might be dealing with an object or an array or
  280. // null.
  281.  
  282. case 'object':
  283.  
  284. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  285. // so watch out for that case.
  286.  
  287. if (!value) {
  288. return 'null';
  289. }
  290.  
  291. // Make an array to hold the partial results of stringifying this object value.
  292.  
  293. gap += indent;
  294. partial = [];
  295.  
  296. // Is the value an array?
  297.  
  298. if (Object.prototype.toString.apply(value) === '[object Array]') {
  299.  
  300. // The value is an array. Stringify every element. Use null as a placeholder
  301. // for non-JSON values.
  302.  
  303. length = value.length;
  304. for (i = 0; i < length; i += 1) {
  305. partial[i] = str(i, value) || 'null';
  306. }
  307.  
  308. // Join all of the elements together, separated with commas, and wrap them in
  309. // brackets.
  310.  
  311. v = partial.length === 0
  312. ? '[]'
  313. : gap
  314. ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
  315. : '[' + partial.join(',') + ']';
  316. gap = mind;
  317. return v;
  318. }
  319.  
  320. // If the replacer is an array, use it to select the members to be stringified.
  321.  
  322. if (rep && typeof rep === 'object') {
  323. length = rep.length;
  324. for (i = 0; i < length; i += 1) {
  325. if (typeof rep[i] === 'string') {
  326. k = rep[i];
  327. v = str(k, value);
  328. if (v) {
  329. partial.push(quote(k) + (
  330. gap
  331. ? ': '
  332. : ':'
  333. ) + v);
  334. }
  335. }
  336. }
  337. } else {
  338.  
  339. // Otherwise, iterate through all of the keys in the object.
  340.  
  341. for (k in value) {
  342. if (Object.prototype.hasOwnProperty.call(value, k)) {
  343. v = str(k, value);
  344. if (v) {
  345. partial.push(quote(k) + (
  346. gap
  347. ? ': '
  348. : ':'
  349. ) + v);
  350. }
  351. }
  352. }
  353. }
  354.  
  355. // Join all of the member texts together, separated with commas,
  356. // and wrap them in braces.
  357.  
  358. v = partial.length === 0
  359. ? '{}'
  360. : gap
  361. ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
  362. : '{' + partial.join(',') + '}';
  363. gap = mind;
  364. return v;
  365. }
  366. }
  367.  
  368. // If the JSON object does not yet have a stringify method, give it one.
  369.  
  370. if (typeof JSON.stringify !== 'function') {
  371. meta = { // table of character substitutions
  372. '\b': '\\b',
  373. '\t': '\\t',
  374. '\n': '\\n',
  375. '\f': '\\f',
  376. '\r': '\\r',
  377. '"': '\\"',
  378. '\\': '\\\\'
  379. };
  380. JSON.stringify = function (value, replacer, space) {
  381.  
  382. // The stringify method takes a value and an optional replacer, and an optional
  383. // space parameter, and returns a JSON text. The replacer can be a function
  384. // that can replace values, or an array of strings that will select the keys.
  385. // A default replacer method can be provided. Use of the space parameter can
  386. // produce text that is more easily readable.
  387.  
  388. var i;
  389. gap = '';
  390. indent = '';
  391.  
  392. // If the space parameter is a number, make an indent string containing that
  393. // many spaces.
  394.  
  395. if (typeof space === 'number') {
  396. for (i = 0; i < space; i += 1) {
  397. indent += ' ';
  398. }
  399.  
  400. // If the space parameter is a string, it will be used as the indent string.
  401.  
  402. } else if (typeof space === 'string') {
  403. indent = space;
  404. }
  405.  
  406. // If there is a replacer, it must be a function or an array.
  407. // Otherwise, throw an error.
  408.  
  409. rep = replacer;
  410. if (replacer && typeof replacer !== 'function' &&
  411. (typeof replacer !== 'object' ||
  412. typeof replacer.length !== 'number')) {
  413. throw new Error('JSON.stringify');
  414. }
  415.  
  416. // Make a fake root object containing our value under the key of ''.
  417. // Return the result of stringifying the value.
  418.  
  419. return str('', {'': value});
  420. };
  421. }
  422.  
  423. // If the JSON object does not yet have a parse method, give it one.
  424.  
  425. if (typeof JSON.parse !== 'function') {
  426. JSON.parse = function (text, reviver) {
  427.  
  428. // The parse method takes a text and an optional reviver function, and returns
  429. // a JavaScript value if the text is a valid JSON text.
  430.  
  431. var j;
  432.  
  433. function walk(holder, key) {
  434.  
  435. // The walk method is used to recursively walk the resulting structure so
  436. // that modifications can be made.
  437.  
  438. var k, v, value = holder[key];
  439. if (value && typeof value === 'object') {
  440. for (k in value) {
  441. if (Object.prototype.hasOwnProperty.call(value, k)) {
  442. v = walk(value, k);
  443. if (v !== undefined) {
  444. value[k] = v;
  445. } else {
  446. delete value[k];
  447. }
  448. }
  449. }
  450. }
  451. return reviver.call(holder, key, value);
  452. }
  453.  
  454. // Parsing happens in four stages. In the first stage, we replace certain
  455. // Unicode characters with escape sequences. JavaScript handles many characters
  456. // incorrectly, either silently deleting them, or treating them as line endings.
  457.  
  458. text = String(text);
  459. rx_dangerous.lastIndex = 0;
  460. if (rx_dangerous.test(text)) {
  461. text = text.replace(rx_dangerous, function (a) {
  462. return '\\u' +
  463. ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  464. });
  465. }
  466.  
  467. // In the second stage, we run the text against regular expressions that look
  468. // for non-JSON patterns. We are especially concerned with '()' and 'new'
  469. // because they can cause invocation, and '=' because it can cause mutation.
  470. // But just to be safe, we want to reject all unexpected forms.
  471.  
  472. // We split the second stage into 4 regexp operations in order to work around
  473. // crippling inefficiencies in IE's and Safari's regexp engines. First we
  474. // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
  475. // replace all simple value tokens with ']' characters. Third, we delete all
  476. // open brackets that follow a colon or comma or that begin the text. Finally,
  477. // we look to see that the remaining characters are only whitespace or ']' or
  478. // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
  479.  
  480. if (
  481. rx_one.test(
  482. text
  483. .replace(rx_two, '@')
  484. .replace(rx_three, ']')
  485. .replace(rx_four, '')
  486. )
  487. ) {
  488.  
  489. // In the third stage we use the eval function to compile the text into a
  490. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  491. // in JavaScript: it can begin a block or an object literal. We wrap the text
  492. // in parens to eliminate the ambiguity.
  493.  
  494. j = eval('(' + text + ')');
  495.  
  496. // In the optional fourth stage, we recursively walk the new structure, passing
  497. // each name/value pair to a reviver function for possible transformation.
  498.  
  499. return typeof reviver === 'function'
  500. ? walk({'': j}, '')
  501. : j;
  502. }
  503.  
  504. // If the text is not JSON parseable, then a SyntaxError is thrown.
  505.  
  506. throw new SyntaxError('JSON.parse');
  507. };
  508. }
  509. }());

JSON字符串转换成JSON对象的更多相关文章

  1. json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值

    一.json相关概念 json,全称为javascript object notation,是一种轻量级的数据交互格式.采用完全独立于语言的文本格式,是一种理想的数据交换格式. 同时,json是jav ...

  2. 特殊字符导致json字符串转换成json对象出错

    在对数据库取出来的数据(特别是描述信息)里面含有特殊字符的话,使用JSON.parse将json字符串转换成json对象的时候会出错,主要是双引号,回车换行等影响明显,左尖括号和右尖括号也会导致显示问 ...

  3. JavaScript:将key和value不带双引号的JSON字符串转换成JSON对象的方法

    遇到相关的问题,花了两天的时间来解决,深感来之不易,所以做如下的总结,希望遇到此问题的码农能更快的找到解决办法! var jsonArr= [{col:TO_CHAR(HZRQ,'YYYYMM'),t ...

  4. js中把JSON字符串转换成JSON对象最好的方法

    在JS中将JSON的字符串解析成JSON数据格式,一般有两种方式: 1.一种为使用eval()函数. 2. 使用Function对象来进行返回解析. 第一种解析方式:使用eval函数来解析,并且使用j ...

  5. js中将json字符串转换成json对象

    在我们使用js请求后台控制器传回的结果result值的时候,经常会出现返回结果值为json字符串的情况,字符串无法在js中直接使用 返回样式栗子: 这是一个json字符串:result = " ...

  6. [转载]将json字符串转换成json对象

    例如: JSON字符串: var str1 = '{ "name": "cxh", "sex": "man" }'; J ...

  7. C#,json字符串转换成Json对象

    将JSON的请求参数转化为C#可序列化对象! JSON请求参数: "{\"id\":1,"name":"张三","dep ...

  8. 将String类型的json字符串转换成java对象

    1,import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper mapper = new ObjectMapper(); Mycl ...

  9. json字符串转换成json增删查改节点

    一.功能实现 1.节点树查询: 按ID查询树 2.节点新增: http://host/tree_data/node/${treeId} in: {node: {key: ..., ...}, pare ...

随机推荐

  1. oracle创建job方法

    oracle创建job方法  alter system enable restricted session;--创建表create table G_TEST ( ID     NUMBER(12), ...

  2. php中的数组定义和使用

    <?php //这个是一个php关于数组的例子,简要的说明了数组的基本使用 //定义一个字符串数组 $fruit = array(\"apple\",\"orang ...

  3. android适应屏幕

    生产android手机的厂商多不胜数,造就了android手机的屏幕尺寸也是不计其数.开发者为了使应用在各个品牌,各个型号的手机屏幕上保持一致的用户体验,就需要运用多种使应用的UI能适应不同屏幕尺寸的 ...

  4. 学习hash_map从而了解如何写stl里面的hash函数和equal或者compare函数

    ---恢复内容开始--- 看到同事用unordered_map了所以找个帖子学习学习 http://blog.sina.com.cn/s/blog_4c98b9600100audq.html (一)为 ...

  5. 2014年辛星完全解读Javascript第一节

    ***************概述*************** 1.Javascript是一种原型化继承的基于对象的动态类型的脚本语言,它区分大小写,主要运行在客户端,用户即使响应用户的操作并进行数 ...

  6. POJ 3274 Gold Balanced Lineup(哈希)

    http://poj.org/problem?id=3274 题意 :农夫约翰的n(1 <= N <= 100000)头奶牛,有很多相同之处,约翰已经将每一头奶牛的不同之处,归纳成了K种特 ...

  7. nginx 域名rewrite跳转

    转自:http://blog.csdn.net/xingfujie/article/details/7337832 需求:nginx规则,所有对OA.bccom.info的访问,redirect到uc ...

  8. java区分大小写,使用TAB进行缩进,public类名只能有一个,而且文件名与类名保持一致.

    java的类必须大写 java区分大小写,使用TAB进行缩进,public类名只能有一个,而且文件名与类名保持一致. 在dos用上下箭头,调用已用过的命令

  9. GridView使用CommandField删除列实现删除时提示确认框

    在.net2005提供的GridView中我们可以直接添加一个CommandField删除列完后在它的RowDeleting事件中完成删除 GridView在使用CommandField删除时弹出提示 ...

  10. linux 和 ecos 内核线程创建/信号量/event等对比

    ecos: int gx_thread_create (const char *thread_name, gx_thread_id *thread_id, void(*entry_func)(void ...