url.toJSON()


URL对象上调用toJSON()方法将返回序列化的URL。返回值与url.hrefurl.toString()的相同。

URL对象使用JSON.stringify()序列化时将自动调用该方法。

const { URL } = require('url');
const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org')
];
console.log(JSON.stringify(myURLs));
  // 输出 ["https://www.example.com/","https://test.example.org/"]

The toJSON() method on the URL object returns the serialized URL. The value returned is equivalent to that of url.href and url.toString().

This method is automatically called when an URL object is serialized with JSON.stringify().

const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org')
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"]