【发布时间】: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'
}
【问题讨论】:
-
在客户端解析它?如果您使用的是 Fetch API,请调用响应的
json方法? -
JSON.parse或response.json如果你正在使用 fetch -
JSON.parse将json转换为对象,但我不知道您所说的“我宁愿将其显示为JavaScript对象”是什么意思。您只是在寻找漂亮的压痕吗? -
(如果有,请看这里:stackoverflow.com/questions/4810841/…)
-
来自 OP 的评论 here,这是 stackoverflow.com/questions/4810841/… 的副本。
标签: javascript node.js