如何更改如何保存在我的DB.json中?
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON中的密钥顺序不应对数据产生任何影响。如果您仍然需要以特定顺序为单位的对象,我将编写自定义功能以串制JSON。这是我想到的代码:
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: