【问题标题】:Getting a JSON and adding it to an array获取 JSON 并将其添加到数组中
【发布时间】:2018-06-13 09:42:08
【问题描述】:

我有以下 JSON 文件:

{
  "fruites": [
          {"id" :"f1", "name": "apple", "selected": "false"},
          {"id": "f2" , "name":"orange", "selected": "false"}
          ]
}


Here is my JSON interface:
export interface FruitsType {

  id: String;
  name: String;
  selected : String;
}

不确定这是否是一个正确的接口。

我想使用水果的名称作为复选框的值

要阅读此 JSON,我有以下服务:

getJSON (): Observable<JSON> {
    return this.http.get<JSON>((this.configUrl))
  }
}

在我的组件中,我有以下代码来读取获取 JSON 文件:

this.jsonService.getJSON().subscribe(response => {


     console.log(response.fruites);
      console.log(response.fruites[1].name);
      console.log(response.fruites.length);

      for (this.i = 0; this.i < response.fruites.length; this.i++) {


          console.log("id" + response.fruites[this.i  ].id);
          console.log("name" + response.fruites[this.i].name);
          console.log("selected" + response.fruites[this.i].selected);


        }

})

在浏览器中我可以看到它可以工作,而在我运行 ng serve 的控制台中我看到以下错误:

src/app/componenets/home/home.component.ts(221,41):错误 TS2339:“JSON”类型上不存在属性“fruites”。

另一件事是我无法将它推送到数组中,我使用以下代码:

this.jsonArray.push(response.fruites[this.i].name )

AND

this.jsonArray.push(response.fruites)

AND

this.jsonArray.push(response)

所有返回未定义或什么都没有!

请咨询我。

【问题讨论】:

  • 发布您的 JSON 类/接口
  • 您是否收到了预期的响应?在 subscibe 方法里面?
  • @Sajeetharan 我现在做到了。如果这就是你的意思
  • 因为错误表明您返回的 JSON 类型没有结果
  • 是的。如下: (2) [{…}, {…}] 0: {id: "f1", name: "apple", selected: "false"} 1: {id: "f2", name: "orange" , selected: "false"} length: 2__proto__: Array(0) orange 2 id: f1 name: apple selected: false id: f2 name: orange selected: false

标签: json angular


【解决方案1】:

我相信你得到的有效载荷可以很容易地做到:

this.jsonService.getJSON().subscribe(response => {
        for(const i of response.fruites) {    // Iterate over the list
           console.log('Data set coming as - ', i);
           console.log('ID - ', i.id);
           console.log('Name - ', i.name);
           console.log('Selected - ', i.selected);
        }
array=[]; var item;
response.fruites.map((item) =>{  array.push(item.name)});
console.log('Array with name', array);`

【讨论】:

  • 嘿。谢谢,这行得通。你能帮我把它添加到数组中吗?因为我需要使用这些 json 作为我的复选框的值
  • 使用与 response.fruites 中相同属性的类。创建该类的实例,您就可以开始了。使用 arrName.push()
  • @Aditya Goswami 感谢您的回复。所以我有一个类如下:export class Fruitrs{ id: string;名称:字符串;选择:字符串;然后我有一个数组: jsonArray : Fruitrs[];然后我执行 This.jsonArray.push(i.name) 这给了我推送错误。如何访问数组的属性以分配 JSON 的特定值?
  • 我在这里使用过地图。希望这会有所帮助。
【解决方案2】:

试试看

response.json().fruites

response.data.fruites

【讨论】:

    【解决方案3】:

    在这个post 中,我发布了关于我如何完成所有事情的完整答案,这也与我提出的这个问题有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2021-11-03
      相关资源
      最近更新 更多