Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...