如何在TypeScript / Angular2 +中访问json数组?

时间:2019-02-05 10:21:57

标签: json angular

我正在尝试访问json数据。我的数据是-

[{"lhs":["GetBook"],"rhs":["BookServiceSOAP"],"confidence":1},{"lhs":
["input"],"rhs":["BookServiceSOAP"],"confidence":1},{"lhs":["ID"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["output"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["Title"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["Author"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["AddBook"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["GetAllBooks"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":["Book"],"rhs":
["BookServiceSOAP"],"confidence":1},{"lhs":
["BookServiceSOAP","GetBook"],"rhs":["output"],"confidence":0.75},{"lhs":
["GetBook","output"],"rhs":["BookServiceSOAP"],"confidence":1},{"lhs":
["BookServiceSOAP","ID"],"rhs":["output"],"confidence":0.75},{"lhs":
["ID","output"],"rhs":["BookServiceSOAP"],"confidence":1},{"lhs":
["BookServiceSOAP","GetAllBooks"],"rhs":["output"],"confidence":0.75},
{"lhs":["GetAllBooks","output"],"rhs":["BookServiceSOAP"],"confidence":1},.....]

当我将其粘贴到onlinejsoneditor.com时,我会得到正确的json输出-

JSON output

但是我无法访问它。

即当我做-

  console.log("parsedData[0] = ", parsedData[0]);

输出为-

  parsedData[0] =  [

我想访问其详细信息,例如lhs,rhs,信心

1 个答案:

答案 0 :(得分:0)

+用作console.log分隔符将在JSON对象上调用toString。这就是为什么您看到[object Object]的原因。使用,,您应该会很好:

console.log('First Response: ', this.parsedData[0]);
console.log('First Response LHS: ', this.parsedData[0].lhs);
console.log('First Response LHS\'s 0th Element: ', this.parsedData[0].lhs[0]);
console.log('First Response RHS: ', this.parsedData[0].rhs);
console.log('First Response RHS\'s 0th Element: ', this.parsedData[0].rhs[0]);
console.log('First Response Confidence: ', this.parsedData[0].confidence);

  

这是您推荐的Working Sample StackBlitz