문제

분명히 jQuery는 주어진 객체 또는 문자열을 JSON 객체로 디코딩 할 수 있습니다. 그러나 서버에 다시 게시 해야하는 JS 객체가 있으며 jQuery에서 json.stringify () 함수를 감싸는 유틸리티가 없습니다. 이 기능은 Chrome, Safari 4, FF3.6 및 IE8에서 발견되지만 이전 브라우저에서는 찾을 수 없습니다. 나는 그것을 지원하는 브라우저에서 기본적으로 사용할 수 있지만, 그렇지 않으면 Crockford의 JSON 스크립트를 사용하는 것으로 돌아와야합니다.

JSON 인코딩 및 디코딩을 처리하는 jQuery가 내장되어 있습니까?

도움이 되었습니까?

해결책

이것을 확인하고 싶을 수도 있습니다.http://www.json.org/js.html

다른 팁

"Closure Library"(Google)를 사용하여 크로스 브라우저 JSON 인코더/디코더를 만들 수 있습니다.

그냥 가십시오 http://closure-compiler.appspot.com/

다음을 텍스트 필드에 삽입 한 다음 "Compile"을 누르십시오.

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @use_closure_library true
// ==/ClosureCompiler==

goog.require('goog.json');
if (!window['JSON']) window['JSON']={};
if (typeof window['JSON']['stringify'] !== 'function') window['JSON']['stringify']=goog.json.serialize;
if (typeof window['JSON']['parse'] !== 'function') window['JSON']['parse']=goog.json.parse;

jQuery는 JSON 현을 기본적으로 디코딩 할 수 있습니다 jQuery.parseJSON().

그러나 인코딩을 위해서는 플러그인 만 알고 있습니다. JQuery-Json

jQuery는 내부적 으로이 기능이 필요하지 않으므로 편의 방법을 제공하지 않습니다.

json.stringify ()는 해당 객체의 json 문자열 표현으로 개체를 인코딩하는 표준이며 권장되는 방법입니다. 많은 브라우저에서 Native JSON 객체의 방법이며 JSON2.JS (https://github.com/douglascrockford/json-js)를 사용하여 폴백을 제공하는 것이 좋습니다.

Stewe의 답변을 구축하려면 Closure Compiler 고급의 켜지면 글로벌 네임 스페이스를 하나의 문자 변수로 오염시키는 스크립트를 제공합니다. 그래서 나는 단지 익명의 함수 호출로 마무리합니다.

(function() { function g(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null"; else if("function"==b&&"undefined"==typeof a.call)return"object";return b};function h(a){a=""+a;if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function i(a,b){var c=[];j(new k(b),a,c);return c.join("")}function k(a){this.a=a} function j(a,b,c){switch(typeof b){case "string":l(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?b:"null");break;case "boolean":c.push(b);break;case "undefined":c.push("null");break;case "object":if(null==b){c.push("null");break}if("array"==g(b)){var f=b.length;c.push("[");for(var d="",e=0;e<f;e++)c.push(d),d=b[e],j(a,a.a?a.a.call(b,""+e,d):d,c),d=",";c.push("]");break}c.push("{");f="";for(e in b)Object.prototype.hasOwnProperty.call(b,e)&&(d=b[e],"function"!=typeof d&&(c.push(f),l(e,c),c.push(":"), j(a,a.a?a.a.call(b,e,d):d,c),f=","));c.push("}");break;case "function":break;default:throw Error("Unknown type: "+typeof b);}}var m={'"':'\\"',"\\":"\\\\","/":"\\/","\u0008":"\\b","\u000c":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},n=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g; function l(a,b){b.push('"',a.replace(n,function(a){if(a in m)return m[a];var b=a.charCodeAt(0),d="\\u";16>b?d+="000":256>b?d+="00":4096>b&&(d+="0");return m[a]=d+b.toString(16)}),'"')};window.JSON||(window.JSON={});"function"!==typeof window.JSON.stringify&&(window.JSON.stringify=i);"function"!==typeof window.JSON.parse&&(window.JSON.parse=h); })();

이제 전화 할 수 있습니다.

var JSONString = JSON.stringify({name: 'value'});

jQuery를 사용할 때는 종종 JSON.stringify () 함수가 필요하지 않습니다. 예를 들어 ajax를 사용하여 JavaScript 데이터를 서버로 보내는 공동 사례를 사용하여 JQuery는 다음을 처리 할 수있는 내장 기능이 있습니다. http://api.jquery.com/category/ajax/)

$.post("test.php", { name: "John", time: "2pm" } );
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
    alert("JSON Data: " + json.users[3].name);
});

위의 모든 예제에서 전송 된 JavaScript 데이터는 jQuery에 의해 자동으로 직렬화됩니다.

이 경우 직렬화는 json.stringify ()와 같지 않으며 대신 데이터가 HTML 쿼리 문자열로 직렬화됩니다 (참조 : 참조 : 참조 :http://en.wikipedia.org/wiki/query_string#structure).

그러나이 형태의 직렬화는 대부분의 (전부는 아니지만) 응용 프로그램에 적합합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top