首页 > 解决方案 > 我可以使用 REST API 获取嵌套在 JSON 对象内的数组的端点路径吗?

问题描述

感谢您的阅读。我有一个 JSON 数据库,其中包含宠物俱乐部的不同成员。

{
"members": [
  {
    "name": "David",
    "rank": "Senior",
    "id": 1,
    "animals": [
      {
        "pet": "Spot",
        "type": "Dog"
    },
    {
        "pet": "Polly",
        "type": "Bird"
    }
    ]
  },
  {
    "name": "Lewis",
    "rank": "Junior",
    "id": 2,
    "animals": [
        {
          "pet": "Fido",
          "type": "Dog"
      },
      {
          "pet": "Luna",
          "type": "Cat"
      }
    ]
  },
  {
    "name": "Sam",
    "rank": "Senior",
    "id": 3,
    "animals": [
        {
          "pet": "Zero",
          "type": "Dog"
      },
      {
          "pet": "Tom",
          "type": "Cat"
      }
      ]
  }
]}

我正在尝试使用 Patch 方法在第一个成员的“动物”数组中添加另一个宠物对象。目前,我能够获取第一个成员的信息(例如 http://localhost:8000/members/1)并使用 PATCH 方法将属性添加到成员对象本身。

const isBanned = { {banned: "March 02, 2021"}  }

const addBanned = () => {

fetch('http://localhost:8000/members/1/', {
    method: 'PATCH',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(isBanned)
    })}

这将返回:

{
"name": "David",
"rank": "Senior",
"id": 1,
"animals": [
  {
    "pet": "Spot",
    "type": "Dog"
},
{
    "pet": "Polly",
    "type": "Bird"
}
],
"banned": "March 02, 2021"
}

不幸的是,我不确定是否可以使用 url 端点来定位动物数组以使用 REST API 添加新的宠物对象。(例如 http://localhost:8000/members/1/animals )。此端点无效!有没有办法让我使用端点来定位 JSON 对象内的嵌套数组?我的目标是将这个宠物添加到大卫:

"pet": "Mittens",
"type": "Cat"

感谢您的任何帮助。

标签: javascriptjsonresturl

解决方案


推荐阅读