【问题标题】:Angular 4 json object from c# rest service来自c#rest服务的Angular 4 json对象
【发布时间】:2018-02-07 04:23:03
【问题描述】:

我有一个简单的服务,它将一个 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 = 数据[0].answer1;

但它给出的变量是未定义的。

这样尝试

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

  }
)

【问题讨论】:

  • 你可以使用 JSON.parse,之后你应该使用这样的东西:obj['GetExamResult']['Answer1']
  • @Nour,这就是我在你之前所说的......你在写之前读过答案吗?

标签: javascript json angular rest service


【解决方案1】:

你可以使用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

【讨论】:

  • 在上面的 json 示例中,我怎样才能只得到问题部分,因为它在 GetExamResult 下。谢谢
  • 我在代码中添加了对您问题的回复。希望能帮到你。告诉我。
【解决方案2】:

data是一个对象,可以直接访问

 this.answer1 = data.answer1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-08
    • 2014-05-23
    • 2017-10-11
    • 2018-04-07
    • 2015-10-10
    • 1970-01-01
    • 2010-09-06
    • 2021-12-14
    相关资源
    最近更新 更多