前端技术之:如何在控制台将JS class实例输出为JSON格式

有一个类:

class Point {

  constructor(x, y) {

    this.x = x;

    this.y = y;

  }

}

如果我们在控制台中输出其实例:

console.log(new Point(10, 20));

 

控制台中的输出结果为:

Point { x: 10, y: 20 }

 

那如何只输出JSON格式,不输出类名”Point”呢?

 

有的同学可能会使用如下的方法:

console.log(JSON.stringify(new Point(10, 20)))

 

这种方法当然是可以的,其输出结果如下:

{"x":10,"y":20}

 

但我们每次输出的时候,都需要调用一次JSON.stringify,显得有些啰嗦。

有没有一种更简洁的办法呢?

答案是肯定的。

实际上,如果你使用的是nodejs,console.log输出类对象时,是调用的inspect函数来序列化并打印输出对象的。

 

而在node中有一种自定义对象inspection函数的办法。

在6.6.0以上版本中,你可以重写类的[util.inspect.custom](depth, options)函数。


const util = require('util');


class Point {

  constructor(x, y) {

    this.x = x;

    this.y = y;

  }


  toString() {

    const that = this;

    return JSON.stringify(that);

  }


  [util.inspect.custom](depth, options) {

    return this.toString()

  }

}

8.x版本的文档说明:https://nodejs.org/docs/latest-v8.x/api/util.html

const inspect = Symbol.for('nodejs.util.inspect.custom');


class Point {

  constructor(x, y) {

    this.x = x;

    this.y = y;

  }


  toString() {

    const that = this;

    return JSON.stringify(that);

  }


  [inspect]() {

    return this.toString()

  }

}


console.log(new Point(10, 20));

在node v10.12.0以上版本中,使用了Symbol,并可以重写[inspect]()函数。

 

相关文档为:https://nodejs.org/api/util.html#util_util_inspect_custom

可以使用HttpClient发送GET请求获取JSON数据,并将其输出控制台。以下是一个示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.json.JSONObject; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(); request.setURI(new URI("https://jsonplaceholder.typicode.com/todos/1")); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = in.readLine()) != null) { result.append(line); } JSONObject jsonObject = new JSONObject(result.toString()); System.out.println(jsonObject.toString()); EntityUtils.consume(response.getEntity()); } } ``` 此代码将向`https://jsonplaceholder.typicode.com/todos/1`发送GET请求,并将返回的JSON数据输出控制台。请注意,我们创建了一个`HttpClient`实例并使用它来执行请求。在响应中,我们读取实体内容并将其换为字符串。然后,我们将字符串换为`JSONObject`并将其输出控制台。最后,我们将实体内容消耗掉,以便可以重复使用连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值