Is there a better way to convert a JSON packet into a query string?
I have an input string that will either be a JSON packet, ala:
{"PHONE":"555-513-4318","FIRSTNAME":"Austin","ARTISTID":"2","LASTNAME":"Weber"}
or a query string, ala:
phone=555-513-4318&firstname=Austin&artistid=2&lastname=Weber
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.
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...
The logic here is that if the string开发者_如何学C 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) { }
This prevents the potential multiple selector and .val()
calls, but the same concept as you're already doing.
精彩评论