如何将服务器发送的JSON字符串转换为JavaScript对象

如何将服务器发送的JSON字符串转换为JavaScript对象,javascript,node.js,Javascript,Node.js,我希望能够将服务器发送的JSON字符串转换为HMTL页面上的JavaScript对象。正在显示原始JSON字符串数据,但我宁愿将其显示为JavaScript对象 case '/get_list': if (req.method == 'POST') { console.log("POST"); var body = ''; req.on('data', function(data) { body += data; console.log("Pa

我希望能够将服务器发送的JSON字符串转换为HMTL页面上的JavaScript对象。正在显示原始JSON字符串数据,但我宁愿将其显示为JavaScript对象

case '/get_list':
  if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function(data) {
      body += data;
      console.log("Partial body: " + body);
    });
    req.on('end', async function() {
      console.log("Body: " + body);
      var json = JSON.parse(body)
      console.log("name is " + json.name) // get name

      const {
        Client
      } = require('pg');
      const connectionString = 'postgresql://postgres:password@localhost/app';

      const client = new Client({
        connectionString: connectionString,
      });
      await client.connect(); // create a database connection

      console.log("user input is " + json.name1);
      //Returns the result from the database in a JSON string onto the HTML page    
      const res3 = await client.query('SELECT name, studentno, proname FROM applications WHERE name =$1 LIMIT 1', [json.name1]);
      await client.end();
      // json = res2.rows;
      json = res3.rows;
      var obj = JSON.parse(res3.rows);
      var json_str_new = JSON.stringify(json); //working
      console.log(obj);
      console.log(json_str_new);
      res.end(json_str_new);
    });

  }
  break;

如果您计划将JSON用于任何事情,比如遍历和读取其中的数据,那么JSON.parse正是您所需要的。漂亮的打印只对人类有用,所以除非你把打印出来的东西专门用于人类消费,否则你的效果应该是好的

但是,如果只显示数据,那么我建议将输出格式化为一些HTML/CSS显示


但是,假设您正计划将数据用于某些事情,正如前面和其他人所提到的,JSON.parse就是生成JS对象所需的一切。

在客户机上解析它?如果您使用的是FetchAPI,是否调用响应的json方法?或者,如果您使用fetchJSON.parse将json转换为对象,但我不知道您的意思,我宁愿将其显示为JavaScript对象。你只是在寻找漂亮的打印缩进吗?如果是的话,请看这里:从OP的评论来看,这是的一个副本。@STEVE.R-请看
Actual results
{"name":"jake","studentno":10001212,"proname":"asdasdas"}

Expected/required results 
{
  name: 'jake',
  studentno: 10001212,
  proname: 'asdasdas'
}