Node | URL.toJSON() Method

The url.toJSON() method in node.js URL module is used to return the serialized URL of the URL object. The return value of this method is equivalent to the URL.href and url.toString() method. If an URL object is serialized using JSON.stringify() method then it is called automatically.

Syntax:

url.toJSON()

Parameters: This method does not accept any parameters.

Return Value: This method returns the serialized URL of the URL object.

Below examples illustrate the url.toJSON() method in Node.js:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// node program to demonstrate the
// url.toJSON() method in node.js
  
// Require an URL module
const url = require('url');
  
// Creating and initializing myURL variable
var urls = [
    new URL('https://www.geeksforgeeks.com'),
    new URL('https://www.google.com'),
    new URL('https://www.mygeeks.com')
];
  
// Display result
console.log(JSON.stringify(urls));

chevron_right


Output:

[
    "https://www.geeksforgeeks.org/",
    "https://www.google.com/",
    "https://www.mygeeks.com/"
]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// node program to demonstrate the
// url.toJSON() method in node.js
  
// Require an URL module
const url = require('url');
  
// Creating and initializing myURL variable
var myurl = [
    new URL('https://www.geeksforgeeks.org'),
];
  
// Display result
console.log(JSON.stringify(myurl));

chevron_right


Output:

[
    "https://www.geeksforgeeks.org/",
    "https://www.contribute.geeksforgeeks.org/",
    "https://www.practice.geeksforgeeks.org/",
    "https://www.demo.geeksforgeeks.org/",
    "https://www.write.geeksforgeeks.org/"
]

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/url.html#url_url_tojson




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.