javascripturlencodequery-stringencodeuricomponent

encodeURI(JSON.stringify()) showing %255B in URL


I am trying to pass along a queryParam in Angular that consists of an array of objects as such fooArray = [{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]. In the URL queryParam I am receiving the following: %255B when using encodeURI(JSON.stringify(this.fooArray))

I have tried using encodeURI(JSON.stringify()) to encode the array into the queryParam and JSON.parse(decodeURIComponent()) to retrieve the param

fooArray = [{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]

fooParam: encodeURI(JSON.stringify(this.fooArray))

JSON.parse(decodeURIComponent(params["fooParam"]))


Solution

  • You're double-encoding the URL. This:

    encodeURI(JSON.stringify([{foo: 'bar', foo: false}, {foo: 'bar', foo: false}]))
    

    results in

    "%5B%7B%22foo%22:false%7D,%7B%22foo%22:false%7D%5D"
    

    If you call encodeURI on it again, you get

    "%255B%257B%2522foo%2522:false%257D,%257B%2522foo%2522:false%257D%255D"
    

    ...because % is encoded as %25.

    Two notes:

    1. You should encode it only once. Perhaps you're passing the string to something that will already URI-encode it for you? If so, don't use encodeURI.

    2. Usually, you want encodeURIComponent, not encodeURI (because usually you're encoding just a component of hte URI, not the entire thing).