Node.js querystring.stringify() Method
Last Updated :
08 Oct, 2021
Improve
The querystring.stringify() method is used to produce an URL query string from the given object that contains the key-value pairs. The method iterates through the object's own properties to generate the query string.
It can serialize a single or an array of strings, numbers, and booleans. Any other types of values are coerced to empty strings.
During serializing, the UTF-8 encoding format is used to encode any character that requires percent-encoding. To encode using an alternative character encoding, the
javascript
Output:
javascript
Output:
encodeURIComponent
option has to be specified.
Syntax:
querystring.stringify( obj[, sep[, eq[, options]]] )Parameters: This function accepts four parameters as mentioned above and described below:
- obj: It is an Object that has to be serialized into the URL query string.
- sep: It is a String that specifies the substring used to delimit the key and value pairs in the query string. The default value is "&".
- eq: It is a String that specifies the substring used to delimit keys and values in the query string. The default value is "=".
- options: It is an Object which can be used to modify the behaviour of the method. It has the following parameters:
- encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is
querystring.escape()
.
- encodeURIComponent: It is a function that would be used to convert URL-unsafe characters to percent-encoding in the query string. The default value is
// Import the querystring module
const querystring = require("querystring");
// Specify the URL object
// to be serialized
let urlObject = {
user: "sam",
access: true,
role: ["admin", "editor", "manager"],
};
// Use the stringify() method on the object
let parsedQuery = querystring.stringify(urlObject);
console.log("Parsed Query:", parsedQuery);
Parsed Query: user=sam&access=true&role=admin&role=editor&role=managerExample 2:
// Import the querystring module
const querystring = require("querystring");
// Specify the URL object
// to be serialized
let urlObject = {
user: "max",
access: false,
role: ["editor", "manager"],
};
// Use the stringify() method on the object
// with sep as `, ` and eq as `:`
let parsedQuery = querystring.stringify(urlObject, ", ", ":");
console.log("Parsed Query 1:", parsedQuery);
// Use the stringify() method on the object
// with sep as `&&&` and eq as `==`
parsedQuery = querystring.stringify(urlObject, "&&&", "==");
console.log("\nParsed Query 2:", parsedQuery);
Parsed Query 1: user:max, access:false, role:editor, role:manager Parsed Query 2: user==max&&&access==false&&&role==editor&&&role==managerReference: https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options