How to escape a JSON string to have it in a URL?
encodeURIComponent(JSON.stringify(object_to_be_serialised))
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
}
});
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