VOOZH about

URL: https://www.geeksforgeeks.org/node-js/node-js-url-tojson-method/

⇱ Node.js URL.toJSON() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Node.js URL.toJSON() Method

Last Updated : 3 Jun, 2026

The URL.toJSON() method in Node.js converts a URL object into a JSON-friendly string representation. It enables URL objects to be serialized automatically, making them easier to store and exchange in structured data formats.

  • Automatically converts URL objects during JSON.stringify().
  • Useful for including URLs in API request and response data.
  • Helps store URL values in JSON-based configuration files.

Syntax

url.toJSON()

where,

  • url: A URL object created using the URL constructor.
  • toJSON(): The method that returns the serialized URL string.

Return Value: Returns the serialized URL as a string. The returned value is equivalent to url.href and url.toString().

Example 1:

Output:

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

Example 2:

Output:

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

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

Use Cases of URL.toJSON() Method

  • Serializing URL objects to JSON: Converts URL objects into string values when generating JSON data.
  • Sending URL data through APIs: Ensures URLs are included in API requests and responses in a standard format.
  • Storing URLs in configuration files: Helps save URL values in JSON-based configuration or settings files.
  • Logging URL information: Produces a clean string representation of a URL for logs and debugging.
  • Exporting application data: Allows URL objects to be safely included when exporting data as JSON.

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

Comment
Article Tags:

Explore