Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

node.js - How to convert JSON string sent from a server into a JavaScript object

I would like to be able to convert the JSON string sent from the server into a JavaScript object on a HMTL page. The raw JSON string data is being displayed, but I would rather display it as a JavaScript object instead.

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'
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're planning on using the JSON for anything, as in traversing and reading the data from that, then JSON.parse() is exactly what you need. Pretty-printing is something only useful for humans, so unless you're exclusively using the output for human consumption, the result you have should be fine.

However, if you are going to just show the data, then I would recommend just formatting the output into some HTML/CSS display.

But assuming you are planning on using the data for something, as mentioned before and by others, JSON.parse() is all you need to generate a JS object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...