Assuming www.mydomain.com?param1=example
as an example.
What is the best way to store a second parameter that is a list of key value pairs? At the minute I use ¶m2=key|value,key|value
. I separate the key from the value using a vertical line, and the pairing with a comma, everything after the equals is encoded using encodeURIComponent()
. This works fine.
However, the user has control of the value... And as sensible human beings we all know that the first thing the user will probably do is stick a vertical bar or a comma as one of the values breaking my parameter parser. Is there a better way to do this? I've seen PHP users talking about storing associated arrays in urls but I'm looking for a pure javascript solution.
To prevent casual tampering, you could add a checksum and base-64 encode your values then encodeURIComponent() the resulting string. (See How can you encode to Base64 using Javascript? and A JavaScript CRC32.)
Of course, this won't prevent someone who's really determined from messing with your values, but it will slow down people who just like to twiddle URLs.
A possible solution would be to escape the pipe and commas in the user input before posting them to your url.
That means sanitising the user input values and replacing
|
and,
with something that doesn't break your code or just stripping them altogether.PHP (and other server-side languages) support passing arrays in the query string.
PHP will parse the GET string as such:
If you don't pass keys, it will be become a numeric array:
Will be parsed as:
UPDATE: You can also parse the query string in JavaScript.
Here is a simple jQuery plugin I made:
Then you can do:
$.parseQuery('param1=example¶m2[]=value1¶m2[]=value2');
.When I think of serializing a list of key-value pairs, I immediately think of using a query-string.
For basics (JSON used to show deserialization):
is essentially:
But special characters have to be escaped:
is essentially:
What this means is that you can pass a query-string as a value in another query-string:
is essentially:
And
foo
can be parsed to produce:That all being said, it's very easy to make mistakes while encoding/decoding, and as soon as you start double-encoding and double-decoding you're guaranteed to run into issues. If you can, use a single query string to contain all the necessary data, and don't embed a query-string within a query-string.