Open In App

Node.js querystring.stringify() Method

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 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:

Return Value: It returns a String that contains the URL query produced from the given object.

Below programs illustrate the querystring.stringify() method in Node.js:

Example 1:




// 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);

Output:

Parsed Query: user=sam&access=true&role=admin&role=editor&role=manager

Example 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);

Output:

Parsed Query 1: user:max, access:false, role:editor, role:manager

Parsed Query 2: user==max&&&access==false&&&role==editor&&&role==manager

Reference: https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options


Article Tags :