Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript object into URI-encoded string

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)

like image 249
jgauffin Avatar asked Mar 28 '12 14:03

jgauffin


People also ask

Can we convert object to string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is encodeURI in JavaScript?

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

What is the difference between encodeURI and encodeURIComponent?

encodeURI is used to encode a full URL. Whereas encodeURIComponent is used for encoding a URI component such as a query string. There are 11 characters which are not encoded by encodeURI , but encoded by encodeURIComponent .

Why is encodeURIComponent needed?

encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL. encodeURI should be used to encode a URI or an existing URL.


2 Answers

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 
like image 157
tipster Avatar answered Oct 12 '22 03:10

tipster


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; } 
like image 22
Grallen Avatar answered Oct 12 '22 02:10

Grallen