Convert JavaScript object into URI-encoded string

encodeuricomponent
encodeuri vs encodeuricomponent
javascript string encoding
convert url to json format online
url encode
javascript form encode object
convert string to url
sanitize query string javascript

I got a JavaScript object which I would like to get x-www-form-urlencoded.

Something like $('#myform').serialize() but for objects.

The following object:

{
    firstName: "Jonas",
    lastName: "Gauffin"
}

would get encoded to:

firstName=Jonas&lastName=Gauffin (do note that special characters should get encoded properly)


Please look closely at both answers I provide here to determine which fits you best.


Answer 1:

Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding.

jsfiddle

encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>");

Result:

%7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D

For those who just want a function to do it:

function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); }

function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); }

Answer 2:

Uses a JSON as a source of key value pairs for x-www-form-urlencoded output.

jsfiddle

// This should probably only be used if all JSON elements are strings
function xwwwfurlenc(srcjson){
    if(typeof srcjson !== "object")
      if(typeof console !== "undefined"){
        console.log("\"srcjson\" is not a JSON object");
        return null;
      }
    u = encodeURIComponent;
    var urljson = "";
    var keys = Object.keys(srcjson);
    for(var i=0; i <keys.length; i++){
        urljson += u(keys[i]) + "=" + u(srcjson[keys[i]]);
        if(i < (keys.length-1))urljson+="&";
    }
    return urljson;
}

// Will only decode as strings
// Without embedding extra information, there is no clean way to
// know what type of variable it was.
function dexwwwfurlenc(urljson){
    var dstjson = {};
    var ret;
    var reg = /(?:^|&)(\w+)=(\w+)/g;
    while((ret = reg.exec(urljson)) !== null){
        dstjson[ret[1]] = ret[2];
    }
    return dstjson;
}

encodeURI(), The encodeURI() function encodes a URI by replacing each instance of certain characters by JavaScript Demo: Standard built-in objects - encodeURI() A new string representing the provided string encoded as a URI. Number · Object · Promise · Proxy · RangeError · ReferenceError · Reflect · RegExp  As a JavaScript developer, you are frequently required to construct URLs with query string parameters when asynchronously calling a RESTful API via XHR.One good way to add query string parameters to the URL is by creating an object and then converting it into a query string.


See jQuery.param(...). Converts to uri, see link for more information!

encodeURIComponent(), The encodeURIComponent() function encodes a URI by replacing each JavaScript Demo: Standard built-in objects - encodeURIComponent() A new string representing the provided string encoded as a URI component. NaN · Number · Object · Promise · Proxy · RangeError · ReferenceError · Reflect  While developing a JavaScript application, you will sometimes want to serialize your data into a plain string. This can be useful for things like: Storing object data in a database Outputting object data to the console for debugging Sending object data over AJAX or to an API The simple syntax for converting an object to […]


I'm surprised that no one has mentioned URLSearchParams

var prms = new URLSearchParams({
  firstName: "Jonas",
  lastName: "Gauffin"
});
console.log(prms.toString());
// firstName=Jonas&lastName=Gauffin

How to Turn an Object into Query String Parameters in JavaScript , Parameter encoding. If you know you're keys and values need to be encoded, you should use encodeURIComponent like this: The String () function converts the value of an object to a string. Note: The String () function returns the same value as toString () of the individual objects.


Since you were asking for a serialized object, this is probably slightly off the mark. But just in case, if your intent is to use the values within that object as individual parameters, this might be the conversion you're looking for:

var params = {
    "param1": "arg1",
    "param2": "arg2"
};
var query = "";
for (key in params) {
    query += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
}
xmlhttp.send(query);

URL-encode JSON, URL-encodes JSON. No ads, popups or nonsense, just a JSON to URL-​encoding converter. This tool converts JavaScript Object Notation (JSON) data to URL-encoding. All special URL Quickly convert a JSON string to JavaScript data. When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type. The result is not always what you expect: 5 + null // returns 5 because null is converted to 0


An extension to @Grallen's Answer 1 – if you need a shorter URL:

Input:

{"q":"SomethingTM","filters":[{"kind":"A","q":"foobar"},{"kind":"B","isntIt":true}],"pagenumber":1}

Output:

('q'~'SomethingTM'_'filters'~!('kind'~'A'_'q'~'foobar')_('kind'~'B'_'isntIt'~true)*_'pagenumber'~1)

Instead of:

%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}

JavaScript encodeURI() Function, () to encode these characters). Tip: Use the decodeURI() function to decode an encoded URI. Return Value: A String, representing the encoded URI  and a string "a.b" how can I convert the string to dot notation so I can go. var val = obj.a.b If the string was just 'a', I could use obj[a]. But this is more complex. I imagine there is some straightforward method but it escapes at present.


JavaScript decodeURIComponent() Function, <link> <map> <mark> <menu> <menuitem> <meta> <meter> <nav> <object> <​ol> Decode a URI after encoding it: var uri = "https://w3schools.com/my test.asp​?name=ståle&car=saab"; Tip: Use the encodeURIComponent() function to encode a URI component. Return Value: A String, representing the decoded URI  Javascript has provided JSON.parse() method to convert a JSON into an object. Once JSON is parsed we can able to access the elements in the JSON. syntax var obj = JSON.parse(JSON); It takes a JSON and parses it into an object so as to access the elements in the provided JSON. Example-1


JSON.stringify(), Convert a JavaScript object into a string with JSON.stringify() . Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj =  Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.


How do I put a JSON object in a URL as a GET parameter? : javascript, JSON itself is a string. To turn your object into JSON you simply need to call a JSON.stringify(obj). Make sure you url-encode the string as well with encodeURI​()  Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation. myJSON is now a string, and ready to be sent to a server: