【发布时间】:2018-08-04 03:21:46
【问题描述】:
我正在使用需要表格来显示数据的 Angular Material 数据表。
我会将后端发送到前端的这种 JSON 数据格式转换为
[{"text":"HELEO"},{"text":"HELEO"},{"text":"popopo"},{"text":":kjnkjn"},{"text":"jhjh"}]
转成这种格式
[ { text: 'HELEO' },
{ text: 'HELEO' },
{ text: 'popopo' },
{ text: 'jhjh' } ]
这是我的服务:
test: nomchamp[];
gettext(): Observable<any> {
return this.http.get<nomchamp[]>(this.url)
.map(res => { console.log(res); return this.test = JSON.parse(res) });
}
在我的后端:
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
console.log(list);
console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
我正在使用 stringify 来通过 res.send 发送数据
使用 JSON.parse 我得到这个错误:
JSON.parse:JSON 数据的第 1 行第 2 列出现意外字符
不使用 parse ,数据不会打印在我的数据表中。
它工作的唯一情况是我在后端使用res.send(res),但我会使用res.write(JSON.stringify(res));
【问题讨论】:
-
您的 JSON = 字符串对吗?因此,
JSON.parse(thatString)将生成一个与您需要的对象相似的对象。也许问题是你没有得到 JSON,而是已经是JSON.parsed 的数据——这就是 JSON.parse 失败的原因——因为 JSON.parse 只接受要解析的字符串
标签: javascript json angular stringify