How to escape a JSON string to have it in a URL?
Solution 1
encodeURIComponent(JSON.stringify(object_to_be_serialised))
Solution 2
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
- 2651 characters using
jQuery.param
- 1691 characters using
JSON.stringify + encodeURIComponent
- 821 characters using
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
- for array: https://stackoverflow.com/a/2790686/467286
- for object.keys: https://stackoverflow.com/a/3937321/467286
Solution 3
You could use the encodeURIComponent
to safely URL encode parts of a query string:
var array = JSON.stringify([ 'foo', 'bar' ]);
var url = 'http://example.com/?data=' + encodeURIComponent(array);
or if you are sending this as an AJAX request:
var array = JSON.stringify([ 'foo', 'bar' ]);
$.ajax({
url: 'http://example.com/',
type: 'GET',
data: { data: array },
success: function(result) {
// process the results
}
});
Solution 4
Using encodeURIComponent()
:
var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),
Solution 5
I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.
Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing =
's. Example:
JSON array-of-strings:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"
The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded %
signs and so on. Base64 is very neutral because it doesn't use special characters.
Matthieu Napoli
I am a software engineer passionate about code and human interactions around it. I like to work with great people, learn and get things done. You can read more about me on my blog or on my GitHub profile. Here are some projects I'm working on: bref.sh: deploy PHP on AWS Lambda to create serverless applications PHP-DI - Dependency injection library for PHP externals.io @matthieunapoli
Updated on July 08, 2022Comments
-
Matthieu Napoli almost 2 years
Using Javascript, I want to generate a link to a page. The parameters to the page are in a Javascript array that I serialize in JSON.
So I would like to generate a URL like that :
http://example.com/?data="MY_JSON_ARRAY_HERE"
How do I need to escape my JSON string (array serialized) to include it as a parameter in a URL ?
If there's a solution using JQuery I'd love it.
Note: Yes, the parameters to the page need to be in an array because there are a lot of them. I think I'll use bit.ly to shorten the links afterwards.
-
w00t almost 9 years
-
-
Matthieu Napoli almost 13 yearsIt seems though that it encodes more characters than necessary (when I paste the link in Firefox, some characters are reverted back (i.e.
{["
). Is there a way to encode only the characters necessary, so that I can shorten my urls ? -
Stoffe over 7 yearsSince 0.1.4 it's also compatible with IE 6-8 if you still need those.
-
Tit Petric almost 7 yearsThere's no need to urldecode() data which comes in PHP $_POST or any other (GET, REQEST, etc.). Depending on what you do from here on, you might be opening yourself for a security issue (SQL injection, etc.)
-
Pradeep Kumar about 6 yearsfinally found the address(%26) of my friend(&) here
-
ingbabic about 4 yearsproblem with base64 strings is that they can contain slash (/) character, which would invalidate url...
-
Chris Johnson about 4 yearsThat’s true but you can choose the characters to use in base64: replace
/
with$
,_
or any other character that doesn’t require url encoding per RFC 3986.