来自c#rest service的Angular 4 json对象

时间:2018-02-07 04:23:04

标签: javascript json angular rest service

我有一个简单的服务,它将json字符串发送到json组件。如何访问组件中json的各个元素。答复如下。

GetExamResult:
"{"Question":"This is the Question","Answer1":"This is 
Answer1","Answer2":"This is Answer2","Answer3":"This is 
Answer3","Answer4":"This is Answer4","Correct":1}"

我试过了     this.answer1 = data [0] .answer1;

但它将变量视为未定义。

尝试这样

getData(){
    this.httpClient.get('someservice')
    .subscribe(
      (data:any[]) => {
        this.ques1 = data[0].GetExamResult.Question1;
        console.log(this.ques1);

  }
)

2 个答案:

答案 0 :(得分:0)

数据是一个对象,可以直接访问为

 this.answer1 = data.answer1;

答案 1 :(得分:0)

您可以使用JSON.parse

var json = '{"result":true, "count":42}';
obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

在您的情况下,例如:

var getExamResult = '{ "Question": "This is the Question", "Answer1": "This is Answer1", "Answer2": "This is Answer2" }';
var obj = JSON.parse(getExamResult);

console.log(obj.Answer1);
// expected output: This is Answer1
console.log(obj.Answer2);
// expected output: This is Answer1