jQuery 将对象转换为 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3904269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Object to JSON string
提问by Kuttan Sujith
jQuery.parseJSON('{"name":"John"}')
converts string representation to object
but I want the reverse. Object is to be converted to JSON string
I got a link http://www.devcurry.com/2010/03/convert-javascript-object-to-json.htmlbut it need to have json2.js do jQuery has a native method to do this?
jQuery.parseJSON('{"name":"John"}')
将字符串表示形式转换为对象,但我想要相反的。对象将被转换为 JSON 字符串我得到了一个链接http://www.devcurry.com/2010/03/convert-javascript-object-to-json.html但它需要有 json2.js 做 jQuery 有一个本机方法来做到这一点?
回答by jAndy
jQuery does only make some regexp checking before calling the native browser method window.JSON.parse()
. If that is not available, it uses eval()
or more exactly new Function()
to create a Javascript object.
jQuery 只在调用本机浏览器方法之前进行一些正则表达式检查window.JSON.parse()
。如果这不可用,它会使用eval()
或更确切地说new Function()
来创建一个 Javascript 对象。
The opposite of JSON.parse()
is JSON.stringify()
which serializes a Javascript object into a string. jQuery does not have functionality of its own for that, you have to use the browser built-in version or json2.js
from http://www.json.org
相反的JSON.parse()
是JSON.stringify()
将 Javascript 对象序列化为字符串。jQuery 没有自己的功能,您必须使用浏览器内置版本或json2.js
来自http://www.json.org
JSON.stringify()
is available in all major browsers, but to be compatible with older browsers you still need that fallback.
JSON.stringify()
可在所有主要浏览器中使用,但要与旧浏览器兼容,您仍然需要后备。
回答by Excalibur
Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.
用于调试目的的 Object.toSource() 也很有用,您希望在其中显示对象及其属性以进行调试。这是一个通用的 Javascript(不是 jQuery)函数,但它只适用于“现代”浏览器。
回答by Subroto Biswas
Convert JavaScript object to json data
将 JavaScript 对象转换为 json 数据
$("form").submit(function(event){
event.preventDefault();
var formData = $("form").serializeArray(); // Create array of object
var jsonConvertedData = JSON.stringify(formData); // Convert to json
consol.log(jsonConvertedData);
});
You can validate json data using http://jsonlint.com
您可以使用http://jsonlint.com验证 json 数据
回答by George Filippakos
You can use the excellent jquery-Json plugin:
你可以使用优秀的 jquery-Json 插件:
http://code.google.com/p/jquery-json/
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
使与 Json 对象之间的转换变得容易。