开发者

JSON to string with jQuery

开发者 https://www.devze.com 2023-03-10 08:27 出处:网络
I know jQuery automatically turns JSON into string when sending AJA开发者_C百科X POST requests. Is it possible to convert JSON to string the same way without sending it via AJAX?Use the JSON stringifi

I know jQuery automatically turns JSON into string when sending AJA开发者_C百科X POST requests. Is it possible to convert JSON to string the same way without sending it via AJAX?


Use the JSON stringifier at JSON.org

http://www.json.org/js.html

BTW I don't think jQuery is converting JSON to a string. I think the conversion of the JSON to a POST message is done internally by the browser as part of the XmlHttpRequest.... but could be wrong... haven't really looked at the code in jQuery for few versions.


Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

See http://www.javascriptkit.com/jsref/json.shtml for more info.

0

精彩评论

暂无评论...
验证码 换一张
取 消