如何更改如何保存在我的DB.json中?

发布于 2025-02-01 23:07:19 字数 947 浏览 4 评论 0原文

我在React应用程序中使用npm I JSON-Server创建了一个假JSON服务器。我已经创建了一个db.json文件,并创建了以下功能,以将新的“任务”推向服务器以保持持久性:

const addTask = async task => {
  const res = await fetch(`http://localhost:5000/tasks`, {
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify(task)
  })

  const data = await res.json()

  setTasks([...tasks, data])
}

现在,这就是我的DB.JSON的保存方式:

{
  "tasks": [
    {
      "id": 1,
      "text": "Doctors Appointment",
      "day": "Feb 5th at 2:30PM",
      "reminder": true
    },
    {
      "text": "SWE Interview",
      "day": "May 9th at 9:30AM",
      "reminder": false,
      "id": 2
    },
    {
      "text": "School Meeting",
      "day": "Feb 11th at 5:30PM",
      "reminder": false,
      "id": 3
    }
  ]
}

ID:ID: 1已手动输入并ID:2和ID:3使用UI。我该如何做到这一点,以便他们遵循与ID相同的安排模式:1 IE ID,文本,日子,然后提醒?

I've created a fake JSON server using npm i json-server in my React application. I've created a db.json file and have created the following function to push a new 'task' to the server for persistence:

const addTask = async task => {
  const res = await fetch(`http://localhost:5000/tasks`, {
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify(task)
  })

  const data = await res.json()

  setTasks([...tasks, data])
}

Now, this is how my db.json is being saved:

{
  "tasks": [
    {
      "id": 1,
      "text": "Doctors Appointment",
      "day": "Feb 5th at 2:30PM",
      "reminder": true
    },
    {
      "text": "SWE Interview",
      "day": "May 9th at 9:30AM",
      "reminder": false,
      "id": 2
    },
    {
      "text": "School Meeting",
      "day": "Feb 11th at 5:30PM",
      "reminder": false,
      "id": 3
    }
  ]
}

id:1 has been manually entered and id:2 and id:3 have been POST'd in using the UI. How can I make it so that they follow the same pattern of arrangement as id:1 i.e. id, text, day then reminder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离笑几人歌 2025-02-08 23:07:19

JSON中的密钥顺序不应对数据产生任何影响。如果您仍然需要以特定顺序为单位的对象,我将编写自定义功能以串制JSON。这是我想到的代码:

function stringifyTask(task) {
    return `{
    "id": ${task.id},
    "text": "${task.text}",
    "day": "${task.day}",
    "reminder": ${task.reminder}
}`
}

Order of keys in JSON should not have any affect on the data. If you still need the object to be in a specific order, I would write custom function to stringify the JSON. Here's the code I came up with:

function stringifyTask(task) {
    return `{
    "id": ${task.id},
    "text": "${task.text}",
    "day": "${task.day}",
    "reminder": ${task.reminder}
}`
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文