我如何使用JSON API规范解析来自端点的JSON?

问题描述 投票:0回答:1

我有一个使用JSON:API规范生成JSON的api端点。 (在后端使用Rails,在前端使用Svelte / Sapper)

我的问题是,有没有一种简单的方法可以在我的JS前端应用程序中使用此JSON?

由于JSON:API规范与基本JSON API分开数据的方式不同,我发现自己不得不不断地深入到JSON中,而不仅仅是能够轻松地引用属性。

我最终会做这样的事情:

data.attributes.start_date

location = data.included.filter(item => item.type === 'location')[0]
location.attributes.name

我也有关系,例如引用某章的克拉斯:

klass = data.included.filter(item => item.type === 'klass')[0]

如何轻松进行klass.chapter.name之类的操作?

是否可以使用一个JS软件包来帮助我使用JSON:API?

这是来自端点的JSON的示例:

{
  "data": {
    "id": "1",
    "type": "program",
    "attributes": {
      "start_date": "2020-04-12T11:42:25.333-04:00",
      "end_date": "2020-07-07T11:42:25.333-04:00"
    },
    "relationships": {
      "klasses": {
        "data": [
          {
            "id": "1",
            "type": "klass"
          },
          {
            "id": "2",
            "type": "klass"
          }
        ]
      }
    }
  },
  "included": [
    {
      "id": "1",
      "type": "klass",
      "attributes": {
        "start_date": "2020-04-12T11:42:25.333-04:00",
        "end_date": "2020-04-12T15:42:25.333-04:00"
      },
      "relationships": {
        "chapter": {
          "data": {
            "id": "1",
            "type": "chapter"
          }
        },
        "program": {
          "data": {
            "id": "1",
            "type": "program"
          }
        }
      }
    },
    {
      "id": "2",
      "type": "klass",
      "attributes": {
        "start_date": "2020-04-19T11:42:25.333-04:00",
        "end_date": "2020-04-19T15:42:25.333-04:00"
      },
      "relationships": {
        "chapter": {
          "data": {
            "id": "2",
            "type": "chapter"
          }
        },
        "program": {
          "data": {
            "id": "1",
            "type": "program"
          }
        }
      }
    },
    {
      "id": "1",
      "type": "chapter",
      "attributes": {
        "id": 1,
        "title": "Chapter 1 Title",
        "introduction": "Chapter 1 introduction"
      }
    },
    {
      "id": "2",
      "type": "chapter",
      "attributes": {
        "id": 2,
        "title": "Chapter 2 Title",
        "introduction": "Chapter 2 introduction"
      }
    },

  ]
}
json json-api
1个回答
0
投票

是否可以使用一个JS软件包来帮助我使用JSON:API?

是,有许多JavaScript客户端库可以帮助使用JSON:API数据:

https://jsonapi.org/implementations/#client-libraries-javascript

© www.soinside.com 2019 - 2024. All rights reserved.