有没有更好的方法将JSON数据包转换为查询字符串? [英] Is there a better way to convert a JSON packet into a query string?

查看:155
本文介绍了有没有更好的方法将JSON数据包转换为查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字符串, 是一个JSON数据包,ala:

I have an input string that will either be a JSON packet, ala:

{"PHONE":"555-513-4318","FIRSTNAME":"Austin","ARTISTID":"2","LASTNAME":"Weber"}

或查询字符串,ala:

or a query string, ala:

phone=555-513-4318&firstname=Austin&artistid=2&lastname=Weber

出于我的目的,我需要 始终 使用后一种格式;所以是JSON数据时,我需要将其转换为查询字符串。它是用户输入,所以我不能保证它将是一个或另一个。

For my purposes, I need to always use the latter format; so when it is JSON data, I need to convert it to a query string. It is user input, so I can't guarantee it will be one or the other.

我正在使用jQuery,并且具有以下代码,这是有效的。我只是想知道是否有更好的方法。

I'm using jQuery, and have the following code, which works. I'm just wondering if there is a better way to go about it.

var data = '';
try {
    data = $.param($.parseJSON($("#content").val()));
} catch (e) {
    data = $("#content").val();
}

//... now do stuff with the `data` var...

这里的逻辑是,如果字符串无效JSON,则 $。parseJSON()将抛出异常,数据将只是设置为用户输入的原始值。

The logic here is that if the string is not valid JSON, then $.parseJSON() will throw an exception, and data will just be set to the original value of the user input.

推荐答案

除了优化它之外,没有更短的方法可以做到这一点。一点点:

There's not a much shorter way to do this, other than optimizing it just a little:

var data = $("#content").val();
try {
  data = $.param($.parseJSON(data));
} catch (e) { }

这可以防止潜力多重选择器和 .val() 来电,但你已经在做同样的概念。

This prevents the potential multiple selector and .val() calls, but the same concept as you're already doing.

这篇关于有没有更好的方法将JSON数据包转换为查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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