Une extension de la réponse 1 de @Grallen - si vous avez besoin d'une URL plus courte :
Entrée :
{"q":"SomethingTM","filters":[{"kind":"A","q":"foobar"},{"kind":"B","isntIt":true}],"pagenumber":1}
Sortie :
('q'~'SomethingTM'_'filters'~!('kind'~'A'_'q'~'foobar')_('kind'~'B'_'isntIt'~true)*_'pagenumber'~1)
Au lieu de :
%7B%22q%22%3A%22SomethingTM%22%2C%22filters%22%3A%5B%7B%22kind%22%3A%22A%22%2C%22q%22%3A%22foobar%22%7D%2C%7B%22kind%22%3A%22B%22%2C%22isntIt%22%3Atrue%7D%5D%2C%22pagenumber%22%3A1%7D
function jsonToUri(v, r, s) {
return encodeURIComponent(
JSON.stringify(v, r, s)
.replace(/[()'~_!*]/g, function(c) {
// Replace ()'~_!* with \u0000 escape sequences
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4)
})
.replace(/\{/g, '(') // { -> (
.replace(/\}/g, ')') // } -> )
.replace(/"/g, "'") // " -> '
.replace(/\:/g, '~') // : -> ~
.replace(/,/g, '_') // , -> _
.replace(/\[/g, '!') // [ -> !
.replace(/\]/g, '*') // ] -> *
)
}
function uriToJson(t, r) {
return JSON.parse(
decodeURIComponent(t)
.replace(/\(/g, '{') // ( -> {
.replace(/\)/g, '}') // ) -> }
.replace(/'/g, '"') // ' -> "
.replace(/~/g, ':') // ~ -> :
.replace(/_/g, ',') // _ -> ,
.replace(/\!/g, '[') // ! -> [
.replace(/\*/g, ']') // * -> ]
, r
)
}
//////// TESTS ////////
var a = {q: 'SomethingTM', filters: [{kind: 'A', q: 'foobar'}, {kind: 'B', isntIt: true}], pagenumber: 1}
var b = jsonToUri(a)
var c = uriToJson(b)
console.log(b)
// ('q'~'SomethingTM'_'filters'~!('kind'~'A'_'q'~'foobar')_('kind'~'B'_'isntIt'~true)*_'pagenumber'~1)
console.log(JSON.stringify(c))
// {"q":"SomethingTM","filters":[{"kind":"A","q":"foobar"},{"kind":"B","isntIt":true}],"pagenumber":1}
var a2 = {"q":"Something(TM)","filters":[{"kind":"A*","q":"foo_bar"},{"kind":"B!","isn'tIt":true}],"page~number":1}
var b2 = jsonToUri(a2)
var c2 = uriToJson(b2)
console.log(b2)
// ('q'~'Something%5Cu0028TM%5Cu0029'_'filters'~!('kind'~'A%5Cu002a'_'q'~'foo%5Cu005fbar')_('kind'~'B%5Cu0021'_'isn%5Cu0027tIt'~true)*_'page%5Cu007enumber'~1)
console.log(JSON.stringify(c2))
// {"q":"Something(TM)","filters":[{"kind":"A*","q":"foo_bar"},{"kind":"B!","isn'tIt":true}],"page~number":1}
0 votes
Demandé auparavant : stackoverflow.com/questions/3848340/
0 votes
Veuillez fournir un exemple d'entrée et de sortie. Si vous souhaitez simplement encoder du JSON,
encodeURIComponent(json)
devrait suffire.