【问题标题】:How to convert JSON string sent from a server into a JavaScript object如何将从服务器发送的 JSON 字符串转换为 JavaScript 对象
【发布时间】:2019-09-04 16:59:33
【问题描述】:

我希望能够将从服务器发送的 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;
Actual results
{"name":"jake","studentno":10001212,"proname":"asdasdas"}

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

【问题讨论】:

标签: javascript node.js


【解决方案1】:

如果您打算将 JSON 用于任何事情,例如遍历和读取其中的数据,那么 JSON.parse() 正是您所需要的。漂亮的打印只对人类有用,所以除非你专门将输出用于人类消费,否则你得到的结果应该没问题。

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

但假设您计划将数据用于某事,正如之前和其他人所提到的,JSON.parse() 是您生成 JS 对象所需的全部内容。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多