URL

URL.prototype.toJSON

Returns a string containing the whole URL, allowing URL objects to be properly serialized with JSON.stringify()

Syntax

JavaScript
url.toJSON()

Return Value

A string of the full URL (same as href)

Examples

Basic Usage
const url = new URL('https://example.com/api')
console.log(url.toJSON())
Practical Example
const data = {
  name: 'API',
  url: new URL('https://api.example.com')
}
console.log(JSON.stringify(data))
Advanced Usage
const urls = [
  new URL('https://example.com'),
  new URL('https://test.com')
]
console.log(JSON.stringify(urls))

Understanding URL.prototype.toJSON

The URL.prototype.toJSON method in JavaScript returns a string containing the whole URL, allowing URL objects to be properly serialized with JSON.stringify(). It belongs to the URL object and is one of the most widely used methods for working with url values in modern JavaScript and TypeScript applications.

The method signature is url.toJSON(). When called, it returns a string of the full url (same as href). Understanding when and how to use toJSON() helps you write more expressive, readable code.

Common use cases for URL.prototype.toJSON include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like url-tostring, url-href, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for URL.prototype.toJSON is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More URL Methods

Other methods in the URL object

Related Tools

More URL Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.