序列化到JSON在jQuery的 [英] Serializing to JSON in jQuery

查看:321
本文介绍了序列化到JSON在jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列化一个对象到JSON。我使用jQuery。是否有一个标准的方式做到这一点?

我的具体情况:我有一个数组定义是这样的:

  VAR国家=新的Array();
国家[0] ='嘎';
国家[1] =CD;
...
 

和我需要把它变成一个字符串传递给 $阿贾克斯()这样的:

  $。阿贾克斯({
    键入:POST,
    网址:Concessions.aspx / GetConcessions
    数据:{'国家':'嘎','CD']},
...
 

解决方案

JSON-JS - JSON在JavaScript

要的对象转换为字符串,可以使用 JSON.stringify

  VAR json_text = JSON.stringify(your_object,空,2);
 

要转换一个JSON字符串对象,使用 JSON.parse

  VAR your_object = JSON.parse(json_text);
 

这是最近建议约翰Resig的的:

  

...请开始迁移   您的JSON-使用的应用程序转移到   克罗克福德的json2.js。它是完全可   与ECMAScript 5兼容   规范和优雅降级   如果本机(快!)实施   存在。

     

其实,我刚刚登陆的jQuery的变化,昨天利用   JSON.parse方法,如果它存在,现在   它已被完全确定。

我倾向于相信他说的话对JavaScript的事项:)

支持的 JSON对象本身。 Crockford的JSON库的当前版本只定义 JSON.stringify JSON.parse ,如果他们不已经定义,留下任何浏览器本机实现完整的。

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

My specific situation: I have an array defined something like this:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...

解决方案

JSON-js - JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);

To convert a JSON string to object, use JSON.parse:

var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

I tend to trust what he says on JavaScript matters :)

Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

这篇关于序列化到JSON在jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆