如何发送PUT HTTP请求到嵌套JSON数据

luaexgnf  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(130)

我有一个JSON文件,需要在其中修改嵌套对象的属性。
我无法在Postman中使用json-server发送PUT请求。
我尝试向http://localhost:3000/data/1/11发送PUT请求,但没有成功。
我不确定如何访问ID为11的元素
我的JSON数据是

{
  "data": [
    {
      "id": "1",
      "name": "Amazon",
      "image": "data:image/png;base64,iVBORw0KGgoAAA",
      "children": [
        {
          "id": "11",
          "name": "Clothes",
          "image": "data:image/png;base64,iVBORw0KG",
          "url": "http://www.google.com"
        },
        {
          "id": "12",
          "name": "Crockery",
          "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ",
          "url": "http://www.google.com"
        },
        {
          "id": "13",
          "name": "Home Appliances",
          "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEA",
          "url": "http://www.google.com"
        }
      ]
    }  
] }
kx1ctssn

kx1ctssn1#

可以使用reduce()filter()通过children id获取子对象

const images = {
"data": [
    {
        "id": "1",
        "name": "Amazon",
        "image": "data:image/png;base64,iVBORw0KGgoAAA",
        "children": [
            {
                "id": "11",
                "name": "Clothes",
                "image": "data:image/png;base64,iVBORw0KG",
                "url": "http://www.google.com"
            },
            {
                "id": "12",
                "name": "Crockery",
                "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ",
                "url": "http://www.google.com"
            },
            {
                "id": "13",
                "name": "Home Appliances",
                "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEA",
                "url": "http://www.google.com"
            }
        ]
    }
]
};
const findImage = ((parent_id, child_id) => {
return result = images.data.reduce((r, o) => {
    const children = o.children.filter(
        ({ id }) => id === child_id && o.id === parent_id);
    if (children.length) {
        r.push(Object.assign({}, o, { children }));
    }
    return r;
}, [])[0];

})

console.log(JSON.stringify(findImage('1', '11'), null, 4));

相关问题