URL: toJSON() method
{{APIRef("URL API")}} {{AvailableInWorkers}}
The toJSON() method of the {{domxref("URL")}}URL interface returns a string representing the URL object. This is the same string that {{domxref("URL.toString()")}} returns.
The method is automatically called by {{jsxref("JSON.stringify()")}} when a URL object is encountered during JSON serialization. The serialized value can then be deserialized using the {{domxref("URL/URL", "URL()")}} constructor within the reviver of {{jsxref("JSON.parse()")}}.
Syntax
toJSON()
Parameters
None.
Return value
A string.
Examples
Calling toJSON() directly
Calling toJSON() directly returns a string containing the URL.
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/toString",
);
const json = url.toJSON();
console.log(json); // https://developer.mozilla.org/en-US/docs/Web/API/URL/toString
console.log(typeof json); // "string"
Serializing to a JSON string
The URL object from the previous example is serialized using {{jsxref("JSON.stringify()")}}, which calls the toJSON() method automatically.
console.log(JSON.stringify(url));
This would log the following JSON string, including the surrounding double quotes, which are part of the string's content:
"https://developer.mozilla.org/en-US/docs/Web/API/URL/toString"
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}