Javascript 如何转义 JSON 字符串以将其包含在 URL 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6807180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to escape a JSON string to have it in a URL?
提问by Matthieu Napoli
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.
使用 Javascript,我想生成一个页面链接。页面的参数位于我在 JSON 中序列化的 Javascript 数组中。
So I would like to generate a URL like that :
所以我想生成一个这样的 URL:
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 ?
我如何需要转义我的 JSON 字符串(数组序列化)以将其作为参数包含在 URL 中?
If there's a solution using JQuery I'd love it.
如果有使用 JQuery 的解决方案,我会喜欢它。
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.
注意:是的,页面的参数需要在一个数组中,因为它们很多。我想我会在之后使用 bit.ly 来缩短链接。
回答by Delan Azabani
encodeURIComponent(JSON.stringify(object_to_be_serialised))
回答by jcj80
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.
我想做同样的事情。对我来说问题是我的网址太长了。我今天使用Bruno Jouhier 的 jsUrl.js 库找到了一个解决方案。
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:
我还没有非常彻底地测试它。但是,以下示例显示了使用 3 种不同方法对同一大对象进行编码后字符串输出的字符长度:
- 2651 characters using
jQuery.param
- 1691 characters using
JSON.stringify + encodeURIComponent
- 821 characters using
JSURL.stringify
- 2651 个字符使用
jQuery.param
- 1691 个字符使用
JSON.stringify + encodeURIComponent
- 821个字符使用
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
显然 JSURL 具有最优化的 urlEncoding js 对象格式。
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Qshows benchmarks for encoding and parsing.
https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q 上的线程 显示了编码和解析的基准。
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.
注意:经过测试,jsurl.js 库似乎使用了 ECMAScript 5 函数,例如 Object.keys、Array.map 和 Array.filter。因此,它只能在现代浏览器上工作(没有即 8 及以下)。但是,这些功能的 polyfill 是否可以使其与更多浏览器兼容。
- for array: https://stackoverflow.com/a/2790686/467286
- for object.keys: https://stackoverflow.com/a/3937321/467286
- 对于数组:https: //stackoverflow.com/a/2790686/467286
- 对于 object.keys:https://stackoverflow.com/a/3937321/467286
回答by Darin Dimitrov
You could use the encodeURIComponent
to safely URL encode parts of a query string:
您可以使用encodeURIComponent
来安全地对查询字符串的部分进行 URL 编码:
var array = JSON.stringify([ 'foo', 'bar' ]);
var url = 'http://example.com/?data=' + encodeURIComponent(array);
or if you are sending this as an AJAX request:
或者如果您将此作为 AJAX 请求发送:
var array = JSON.stringify([ 'foo', 'bar' ]);
$.ajax({
url: 'http://example.com/',
type: 'GET',
data: { data: array },
success: function(result) {
// process the results
}
});
回答by genesis
Using encodeURIComponent()
:
使用encodeURIComponent()
:
var url = 'index.php?data='+encodeURIComponent(JSON.stringify({"json":[{"j":"son"}]})),
回答by Chris Johnson
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.
我会提供一个奇怪的选择。有时使用不同的编码更容易,尤其是当您处理各种系统时,这些系统并非都以相同的方式处理 URL 编码的细节。这不是最主流的方法,但在某些情况下可以派上用场。
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:
您可以对数据进行 base64 编码,而不是对数据进行 URL 编码。这样做的好处是编码数据非常通用,仅包含字母字符,有时包含尾随=
的 。例子:
JSON array-of-strings:
JSON 字符串数组:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
该数据,URL 编码为data
参数:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
同样,base64 编码:
"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.
base64 方法可以更短一些,但更重要的是它更简单。我经常在 cURL、Web 浏览器和其他客户端之间移动 URL 编码的数据时遇到问题,通常是由于引号、嵌入的%
标志等。Base64 非常中立,因为它不使用特殊字符。
回答by foxybagga
Answer given by Delan is perfect. Just adding to it - incase someone wants to name the parameters or pass multiple JSON strings separately - the below code could help!
Delan给出的答案是完美的。只需添加它 - 如果有人想要命名参数或分别传递多个 JSON 字符串 - 下面的代码可能会有所帮助!
JQuery
查询
var valuesToPass = new Array(encodeURIComponent(VALUE_1), encodeURIComponent(VALUE_2), encodeURIComponent(VALUE_3), encodeURIComponent(VALUE_4));
data = {elements:JSON.stringify(valuesToPass)}
PHP
PHP
json_decode(urldecode($_POST('elements')));
Hope this helps!
希望这可以帮助!