encodeURIComponent(JSON.stringify(object_to_be_serialised))
Answer from Delan Azabani on Stack Overflow
🌐
Medium
medium.com › @shlomisderot › javascript-parse-url-encoded-string-into-json-in-one-line-of-code-f1cbed4ba09c
Javascript — Parse URL-encoded string into JSON in ONE line of code | by Shlomi Elbaz | Medium
March 22, 2023 - JSON.parse(decodeURIComponent('url encoded string').replace(/=([^&]+)\&/g, "=\"$1\",\n\r").replace(/(^|\r)([^=]+)=/g, "\"$2\":").replace(/^/, '{').replace(/$/, '}'))
Discussions

How do I put a JSON object in a URL as a GET parameter?

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() before appending it to a link

More on reddit.com
🌐 r/javascript
25
13
December 25, 2017
javascript - How to convert Encoded url into JSON format? - Stack Overflow
OP wants to convert the form data ... into JSON using javascript APIs but you have converted the whole URL instead. You don't convert it into JSON format in the end. 2017-05-25T11:54:25.963Z+00:00 ... The decodeURIComponent function will convert URL encoded characters back to ... More on stackoverflow.com
🌐 stackoverflow.com
jquery - Convert JavaScript object into URI-encoded string - Stack Overflow
I got a JavaScript object which I would like to get x-www-form-urlencoded. Something like $('#myform').serialize() but for objects. ... T.J. Crowder · 1.1m201201 gold badges2k2k silver badges2k2k bronze badges ... Please provide an example input and output. If you want simply want to encode JSON, ... More on stackoverflow.com
🌐 stackoverflow.com
Is it possible to compress JSON to a string of safe characters that can be used in a URL query string?

Yes. Though be careful of URL length limits some older browsers and proxy servers will impose.

More on reddit.com
🌐 r/javascript
31
18
September 9, 2016
🌐
Code Beautify
codebeautify.org › json-url-encode
JSON URL Encode to encode JSON text to url encode.
JSON URL Encoded is easy to use tool to Encode Plain JSON data with a URL encode. Copy, Paste and Encode. It helps to encode your JSON data to Plain JSON. It uses the encodeURIComponent method of JavaScript to encode the data.
🌐
Online Tools
onlinetools.com › json › url-encode-json
URL-encode JSON – Online JSON Tools
Free online JSON to URL-encoding converter. Just load your JSON in the input field and it will automatically get converted to URL-encoded JSON. In the tool options, you can choose whether to use lowercase or uppercase letters for the hexadecimal ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › encodeURI
encodeURI() - JavaScript - MDN Web Docs
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).
Find elsewhere
Top answer
1 of 12
82

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
2 of 12
66

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;
}
🌐
IQCode
iqcode.com › code › javascript › javascript-urlencode-json
javascript urlencode json Code Example
//url encode json encodeURIComponent(JSON.stringify(object_to_be_serialised))
🌐
GitHub
gist.github.com › lastguest › 1fd181a9c9db0550a847
Convert JavaScript object to x-www-form-urlencoded format · GitHub
/** * @param {Object} object * @return {string} */ export function toFormUrlEncoded(object) { return Object.entries(object) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`) .join('&'); } ... x = {a: 1, b: { c: 3, d: "asdf & hahaha" }} JSON_to_URLEncoded(x) // "a=1&b[c]=3&b[d]=asdf & hahaha" toFormUrlEncoded(x) // "a=1&b=[object Object]"
🌐
JSON Formatter
jsonformatter.org › json-url-encode
Best JSON URL Encode Online
Online JSON URL Encode tool to convert JSON to URL encoded.
🌐
npm
npmjs.com › package › urlcode-json
urlcode-json - npm
December 2, 2013 - This is a tool for converting JSON object to an urlencode string like python's urllib.urlencode() method or decode an url to a JSON object. var str_1 = urlcodeJson.encode( { "name" : "cashlee" , "language" : "中文" } , true ); var str_2 = ...
      » npm install urlcode-json
    
Published   Dec 02, 2013
Version   0.0.5
Author   CashLee
🌐
Google Groups
groups.google.com › g › node-red › c › GP0Y4y-nHD4
How can I take json and encode into a URL
Mark - I did a encodeURIComponent and ended up with and [object] [object] so I added a JSON.stringify. The stringify escapes each quote and it seems like this is not needed. So I may remove the escape characters with a replace command. Overall this seems to work! var urlBody = { "selection": { "includeAlerts": "false", "selectionType": "registered", "selectionMatch": "", "includeEvents": "false", "includeSettings": "false", "includeRuntime": "true", "includeSensors": "true" } }; var urlBodyStr = JSON.stringify(urlBody); var encodedBody = encodeURIComponent(urlBodyStr); msg = { "url": "https://api.ecobee.com/1/thermostat?format=json&body=" + encodedBody, "method": "GET", headers: { "Content-Type": "application/json;charset=UTF-8", "Authorization": "Bearer " + flow.get('EcobeeAccessToken'), } Dave - I think this is what you suggested (see below).
🌐
GitHub
github.com › masotime › json-url
GitHub - masotime/json-url: Compress JSON into compact base64 URI-friendly notation · GitHub
For small JS objects, LZW largely outperformed LZMA, but for the most part you'd probably be looking to compress large JSON data rather than small amounts (otherwise a simple stringify + base64 is sufficient). You can choose to use whatever codec suits you best. In addition, there is now support for LZSTRING, although the URI encoding still uses urlsafe-base64 because LZSTRING still uses unsafe characters via their compressToURIEncodedString method - notably the + character
Starred by 247 users
Forked by 19 users
Languages   JavaScript
🌐
jsonurl
jsonurl.org
JSON inside a URL
A JavaScript library to serialize/deserialize arbitrary JSON text to/from a clob suitable for use in a URL query string. The primary goal is to optimize for size rather than readability. It offers several compression options and looks quite complete. ... A JavaScript library for encoding and decoding JavaScript objects to/from a URL compatible string...
🌐
Online Tools
onlinetools.com › json › url-decode-json
URL-decode JSON – Online JSON Tools
This tool converts previously URL-escaped JavaScript Object Notation (JSON) data back to plain-text JSON, which you can read and edit. The process of encoding and passing JSON data in URLs is called URL encoding. It converts special characters ...
🌐
GitHub
github.com › Sage › jsurl
GitHub - Sage/jsurl: URL-friendly JSON · GitHub
There is no risk of missing a URL encoding/decoding pass, or of messing up a JSURL string by applying an extra URL encoding or decoding pass. ... Property names unquoted (but escaped -- see below). String values prefixed by a single quote (') and escaped · All other JSON punctuation (colon : and comma ,) replaced by tildes (~)
Starred by 396 users
Forked by 30 users
Languages   JavaScript
🌐
Medium
manterapj.medium.com › how-to-pass-a-json-object-in-a-url-c46044e91c0d
How to pass a JSON object in a URL? | by Pankaj Yadav | Medium
January 7, 2023 - let myObject = { name: 'John', age: 30 }; let encodedObject = encodeURIComponent(JSON.stringify(myObject)); let url = '/my/url?object=' + encodedObject;