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 is not valid JSON, then $.parseJSON()
will throw an exception, and data will just be set to the original value of the user input.