JSON-js - JavaScript中的JSON。
要将对象转换为字符串,请使用JSON.stringify
:
var json_text = JSON.stringify(your_object, null, 2);
要将JSON字符串转换为对象,请使用JSON.parse
:
var your_object = JSON.parse(json_text);
John Resig 最近推荐:
...请开始将使用 JSON 的应用程序迁移到 Crockford 的 json2.js。它完全兼容 ECMAScript 5 规范,如果存在本地(更快!)实现,则会优雅地降级。
事实上,我昨天刚在 jQuery 中引入了一个变化,利用了 JSON.parse 方法,现在它已经完全指定。
在 JavaScript 方面,我倾向于相信他的话 :)
所有现代浏览器(以及许多不古老的旧浏览器)都原生支持 JSON 对象。Crockford 的 JSON 库的当前版本仅在未定义时才定义 JSON.stringify
和 JSON.parse
,使任何浏览器本地实现保持不变。
JSON.stringify(obj, function(key, val) { if (val instanceof SVGSVGElement) {return val.xml || new XMLSerializer().serializeToString(val);} return val;})
- Courtney Christensen我已经使用jquery-json进行了6个月,它非常好用。使用起来非常简单:
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);
// Result: {"foo":"bar","baz":"wockaflockafliz"}
我没有用过,但你可以尝试由Mark Gibson编写的 jQuery插件
它添加了两个函数:$.toJSON(value)
,$.parseJSON(json_str, [safe])
。
$.parseJSON
已经是jQuery核心的一部分。 - Marnen Laibow-Koser不,将数据序列化为JSON的标准方式是使用现有的JSON序列化库。如果您不想这样做,那么您就需要编写自己的序列化方法。
如果您需要指导如何操作,我建议您检查一些可用库的源代码。
编辑: 我不会明确表示编写自己的序列化方法是不好的,但您必须考虑到,如果对于您的应用程序来说使用格式正确的JSON很重要,那么您必须衡量“一个更多依赖”的开销和您的自定义方法可能某天会遇到您没有预料到的故障情况之间的风险。是否接受这种风险取决于你自己。
我确实在某处找到了这个信息。虽然我记不清具体在哪里了...可能是在 StackOverflow 上 :)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var data = "" + $.toJSON($('form').serializeObject());
。data现在是一个JSON字符串。之后运行此代码:alert(typeof data);
,它应该会弹出"string"。然后运行此代码:alert(data);
,你应该会看到JSON文本。最后,前往http://jsonlint.com并粘贴JSON字符串。它应该被验证为“Valid JSON”。我不确定我是否理解你的意思,因为一切似乎都指向这将生成有效的JSON。再次感谢。 - jamesmortensen$.toJSON 不是一个函数
的问题,所以我包含了 <script src="http://www.x-non.com/json/jquery.json-2.4.min.js"> </script>
。 - rubo77$.toJSON
替换为JSON.stringify
,在不需要外部依赖项的情况下获得相同的结果,假设您只支持现代浏览器。希望这可以帮助您! :) - jamesmortensen.toSource()
,但它并不完全跨浏览器兼容。在调用$.ajax
之前,您应该对Json_PostData
使用JSON.stringify
和JSON.parse
:
$.ajax({
url: post_http_site,
type: "POST",
data: JSON.parse(JSON.stringify(Json_PostData)),
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );
},
success: function (data) {
alert("write json item, Ajax OK");
}
});
这基本上是一个2步骤的过程:
首先,您需要像这样进行字符串化:
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
接下来,您需要将 string
转换为 Object
:
var obj = JSON.parse(JSON_VAR);
最好的方法是包含JSON对象的polyfill。
但是,如果您坚持在jQuery命名空间中创建一个将对象序列化为JSON表示法(JSON的有效值)的方法,您可以像这样做:
// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
var _PRIMITIVE, _OPEN, _CLOSE;
if (window.JSON && typeof JSON.stringify === "function")
return JSON.stringify;
_PRIMITIVE = /string|number|boolean|null/;
_OPEN = {
object: "{",
array: "["
};
_CLOSE = {
object: "}",
array: "]"
};
//actions to execute in each iteration
function action(key, value) {
var type = $.type(value),
prop = "";
//key is not an array index
if (typeof key !== "number") {
prop = '"' + key + '":';
}
if (type === "string") {
prop += '"' + value + '"';
} else if (_PRIMITIVE.test(type)) {
prop += value;
} else if (type === "array" || type === "object") {
prop += toJson(value, type);
} else return;
this.push(prop);
}
//iterates over an object or array
function each(obj, callback, thisArg) {
for (var key in obj) {
if (obj instanceof Array) key = +key;
callback.call(thisArg, key, obj[key]);
}
}
//generates the json
function toJson(obj, type) {
var items = [];
each(obj, action, items);
return _OPEN[type] + items.join(",") + _CLOSE[type];
}
//exported function that generates the json
return function stringify(obj) {
if (!arguments.length) return "";
var type = $.type(obj);
if (_PRIMITIVE.test(type))
return (obj === null ? type : obj.toString());
//obj is array or object
return toJson(obj, type);
}
}(jQuery));
var myObject = {
"0": null,
"total-items": 10,
"undefined-prop": void(0),
sorted: true,
images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
position: { //nested object literal
"x": 40,
"y": 300,
offset: [{ top: 23 }]
},
onChange: function() { return !0 },
pattern: /^bg-.+\.(?:png|jpe?g)$/i
};
var json = jQuery.stringify(myObject);
console.log(json);
countries
是一个变量名,而不是一个键名……当你尝试将其序列化时,这个信息会丢失。 - mpen