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
URLconstructor. - 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:
// node program to demonstrate the
// url.toJSON() method in node.js
// Require an URL module
const url = require('url');
// Creating and initializing myURL variable
let urls = [
new URL('https://www.geeksforgeeks.com/'),
new URL('https://www.google.com/'),
new URL('https://mygeeks.com/')
];
// Display result
console.log(JSON.stringify(urls));
Output:
[
"https://www.geeksforgeeks.org//",
"https://www.google.com//",
"https://mygeeks.com//"
]
Example 2:
// node program to demonstrate the
// url.toJSON() method in node.js
// Require an URL module
const url = require('url');
// Creating and initializing myURL variable
let myurl = [
new URL('https://www.geeksforgeeks.org/'),
new URL('https://write.geeksforgeeks.org//'),
new URL('https://www.practice.geeksforgeeks.org'),
new URL('https://www.demo.geeksforgeeks.org'),
new URL('https://write.geeksforgeeks.org//'),
];
// Display result
console.log(JSON.stringify(myurl));
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.