【发布时间】:2016-12-09 00:52:02
【问题描述】:
我正在尝试从 json 数组中读取值以显示在页面中。我已经尝试使用下面的代码,但无法做到。我尝试了很长时间才完成这项工作,请告知我在这里做错了什么。
我也无法执行 JSON.parse- 意外输入错误。
http.request(options, function(res) {
res.on('data', function (result) {
console.log(result);//Displaying below format of result without any error
console.log(result.Reference[0].name); Error //TypeError: Cannot read property '0' of undefined.
console.log(result.Reference.length);//Error TypeError: Cannot read property 'length' of undefined
JSON 格式:打印结果时
{
"Reference": [
{
"name": "xxxxxxxx",
"typeReference": {
"articulation": 0,
"locked": false,
"createdBy": {
"userName": "System",
},
"lastModifiedBy": {
"userName": "System",
},
"lastModified": 1391084398660,
"createdOn": 1391084398647,
"isSystem": true
},
"communityReference": {
"name": "xxxxxx",
"language": "English",
"sbvr": false,
"parentReference": {
"name": "xxxxx",
"sbvr": false,
"meta": false,
"parentReference": null,
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxx",
},
"lastModified": 1459185726230,
"createdOn": 1456337723119,
"isSystem": false
},
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxxx",
},
"lastModified": 1472655031590,
"createdOn": 1472654988012,
"isSystem": false
},
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxx",
"firstName": "xxxxx",
},
"lastModified": 1473171981520,
"createdOn": 1472655253366,
"isSystem": false
},
{
"name":"yyyyyy", same attribute type as above.
...
},
{
..
},
【问题讨论】:
-
您检查过您的
result不是字符串吗? -
如果您在执行
JSON.parse(result)时遇到意外的输入错误,那么它可能不是有效的 JSON。 -
如果result是字符串,首先需要将其转换为对象
var obj = JSON.parse(result); obj.Reference[0]; -
我已经使用 typeof(result) 验证了结果是字符串。
标签: javascript json node.js node-request