Open In App

How to serialize an object to query string using jQuery ?

Given a jQuery object and the task is to serialize the object element into the query string using jQuery. To serialize an object we can use different approaches.

Below are the following approaches:



Approach 1: Using JSON.stringify() method and jQuery() param() Method

Example: This example uses the param() method to serialize the object. 




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
          Serialize an object to query string
      </title>
      <script src=
      </script>
</head>
   
<body
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p>
        Click the button to serialize
          the object to query string;
    </p>
   
    <button>
        click here
    </button>
   
      <p id="result"></p>
   
    <script>
        const data = {
            param1: 'val_1',
            param2: 'val_2',
            param3: 'val_3'
        };
       
        JSON.stringify(data);
         
          $('button').on('click', function () {
            const result = $.param(data);
            $('#result').text(result);
        });
    </script>
</body>
 
</html>

Output:



Approach 2: Using keys() and map() Methods

Example: This example creates a function which is taking each key, and value pair and appends them as a string to get the query string keys() and map() method




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Serialize an object to query string
    </title>
    <script src=
    </script>
</head>
 
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p>
        Click the button to serialize
        the object to query string
    </p>
 
    <button>
        click here
    </button>
    <p id="result"></p>
 
    <script>
        const data = {
            param1: 'val_1',
            param2: 'val_2',
            param3: 'val_3'
        };
       
        JSON.stringify(data);
 
        function convert(json) {
            return '?' +
                Object.keys(json).map(function (key) {
                    return encodeURIComponent(key) + '=' +
                        encodeURIComponent(json[key]);
                }).join('&');
        }
        $('button').on('click', function () {
            const result = convert(data);
            $('#result').text(result);
        });
    </script>
</body>
 
</html>

Output:


Article Tags :