简体   繁体   English

我无法将动态数据附加到我的 JSON 文件

[英]I am having trouble appending dynamic data to my JSON file

I have been having a bit of trouble appending new dynamic data to a JSON file.我在将新的动态数据附加到 JSON 文件时遇到了一些麻烦。 To sum up my project, I take in the projectName from an input form at the /new page.总结一下我的项目,我从/new页面的输入表单中获取 projectName。 My API is then using the node.js's fs module to create a new JSON file with which I can then append the new dynamic data upon subsequential requests to my form.然后我的 API 正在使用 node.js 的 fs 模块创建一个新的 JSON 文件,然后我可以使用它 append 对我的表单进行后续请求时获得新的动态数据。 The variables are 1) projectName (is taken in from my form), 2) activeUser (which is programmed in through an environmental variable), 3) is the date of the request which I am acquiring through a timestamp variable with this function:变量是 1) projectName (取自我的表单), 2) activeUser (通过环境变量编程), 3) 是我通过时间戳变量获取的请求的日期与此 function:

const timestamp = (JSON.parse(JSON.stringify(new Date())));

All three of these variables seem to print correctly for 2 subsequent requests and then on the third form submission there seems to be no new data appending to the JSON file.对于 2 个后续请求,所有这三个变量似乎都正确打印,然后在第三个表单提交时,似乎没有新数据附加到 JSON 文件。 However i am relatively new to node.js and I can't seem to figure out where I am messing this up.但是我对 node.js 比较陌生,我似乎无法弄清楚我在哪里搞砸了。

This is my API这是我的 API

pages/api/demos/index.js页面/api/demos/index.js

import dbConnect from '../../../lib/dbConnect';
import Demo from '../../../models/Demo';
import fs from 'fs';

export default async function handler(req, res) {
  const {
    query: { id },
    method,
  } = req
  await dbConnect()

  switch (method) {
    case 'POST':
      try {
          //check if file exist
          if (!fs.existsSync('projects.json')) {
              //create new file if not exist
              fs.closeSync(fs.openSync('projects.json', 'w'));
          }
          // read file
          const timestamp = (JSON.parse(JSON.stringify(new Date())));
          const newFileName = req.body.projectName;
          const activeUser = process.env.ACTIVE_USERNAME;
          const file = fs.readFileSync('projects.json')
          const data = {
            "projects": [
                {
                    "username": activeUser,
                    "pages": [
                        {
                            "display": "routes",
                            "subpages": [
                                {
                                    "date": timestamp,
                                    "route": newFileName,
                                    "display": newFileName
                                }
                            ]
                        }
                    ]
                }
            ]
        }
          //check if file is empty
          if (file.length == 0) {
              //add data to json file
              fs.writeFileSync("projects.json", JSON.stringify([data]))
          } else {
              //append data to jso file
              const json = JSON.parse(file.toString())
              //add json element to json object
              json.push(data);
              fs.appendFileSync("projects.json", JSON.stringify(data))
          }

        const demo = await Demo.create(
          req.body
        )
        res.status(201).json({ success: true, data: demo })
      } catch (error) {
        res.status(400).json({ success: false })
      }
      break
    default:
      res.status(400).json({ success: false })
      break
  }
}


After the first form submission my JSON file projects.json looks like在第一次提交表单后,我的 JSON 文件projects.json看起来像

[
    {
        "projects": [
            {
                "username": "projectmikey",
                "pages": [
                    {
                        "display": "routes",
                        "subpages": [
                            {
                                "date": "2022-09-12T19:03:09.547Z",
                                "route": "1",
                                "display": "1"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

and then after the 2nd form submission然后在第二次提交表单之后

[
    {
        "projects": [
            {
                "username": "projectmikey",
                "pages": [
                    {
                        "display": "routes",
                        "subpages": [
                            {
                                "date": "2022-09-12T19:03:09.547Z",
                                "route": "1",
                                "display": "1"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]{
    "projects": [
        {
            "username": "projectmikey",
            "pages": [
                {
                    "display": "routes",
                    "subpages": [
                        {
                            "date": "2022-09-12T19:03:24.466Z",
                            "route": "2",
                            "display": "2"
                        }
                    ]
                }
            ]
        }
    ]
}

Oddly it seems to work for two form submissions and then the data stops appending to my file.奇怪的是,它似乎适用于两个表单提交,然后数据停止附加到我的文件中。 This is after the third attempt, (no change to the file)这是第三次尝试之后,(文件没有变化)

[
    {
        "projects": [
            {
                "username": "projectmikey",
                "pages": [
                    {
                        "display": "routes",
                        "subpages": [
                            {
                                "date": "2022-09-12T19:03:09.547Z",
                                "route": "1",
                                "display": "1"
                            }
                        ]
                    }
                ]
            }
        ]
    }
]{
    "projects": [
        {
            "username": "projectmikey",
            "pages": [
                {
                    "display": "routes",
                    "subpages": [
                        {
                            "date": "2022-09-12T19:03:24.466Z",
                            "route": "2",
                            "display": "2"
                        }
                    ]
                }
            ]
        }
    ]
}

It seems to stop working at all when I remove the pair of brackets around the initial JSON object.当我移除初始 JSON object 周围的一对括号时,它似乎完全停止工作。 The line I am refering to is fs.writeFileSync("projects.json", JSON.stringify([data]))我指的是fs.writeFileSync("projects.json", JSON.stringify([data]))

I could really use another pair of eyes on this so I can see where I am messing this up.我真的可以用另一双眼睛来解决这个问题,这样我就可以知道我在哪里搞砸了。 lol Thanks in advance for your time...大声笑提前感谢您的时间...

Although it feels like you are "appending" to the file, you are actually doing something more complicated.虽然感觉像是在“附加”到文件中,但实际上你在做一些更复杂的事情。

eg before state:例如在 state 之前:

[ "one", "two" ]

desired after-state:所需的后状态:

[ "one", "two", "three" ]

Notice that you can't just append text to the before-state JSON because there's already that pesky ] terminating the whole object.请注意,您不能只将 append 文本写入前状态 JSON,因为已经有那个讨厌的]终止整个 ZA8CFDE6331BD59EB2AC96F8911C4B6666Z。

Some failed attempts might look like:一些失败的尝试可能如下所示:

failed attempt to append another entire array尝试 append 另一个整个阵列失败

[ "one", "two" ][ "three" ]

This is invalid because there are two root objects.这是无效的,因为有两个根对象。

failed attempt to append just the rest of the array尝试 append 只是阵列的 rest 失败

[ "one", "two" ], "three" ]

That's no good either.那也不好。 The ] at the end of the original file needs to be overwritten or removed, so there's no way to just append.原始文件末尾的]需要被覆盖或删除,因此无法仅使用 append。 I suppose technically you could seek to the position of the final ] and then continue writing an incomplete object from there.我想从技术上讲,您可以寻找最终的 position ] ,然后从那里继续编写不完整的 object。 But this is very awkward to remove the final ] from the source and to remove the initial [ from the chunk you're trying to append.但是从源中删除最后的]并从您尝试 append 的块中删除初始的[是非常尴尬的。 It's just a difficult approach.这只是一个困难的方法。

What you actually want to do is:你真正想做的是:

  1. read the entire JSON file读取整个 JSON 文件
  2. parse the JSON into a JavaScript object (or create an empty object if the file didn't exist)将 JSON 解析为 JavaScript object (或创建一个空的 ZA8CFDE6331BD59EB66AC96F8911ZC4 文件不存在)
  3. Modify the JavaScript object as necessary (eg push into the array to add another element)根据需要修改 JavaScript object(例如push入数组以添加另一个元素)
  4. stringify the JavaScript object into new JSON将 JavaScript object 字符串化为新的 JSON
  5. overwrite the entire file with the new JSON.用新的 JSON 覆盖整个文件。

 /* In Node.js: const fs = require('fs'); try { initialJSON = fs.readFileSync('example.json'); } catch (ignore) { initialJSON = '[]'; } */ /* Mocked for this example: */ initialJSON = '["one","two"]'; // Common obj = JSON.parse(initialJSON); obj.push("three"); finalJSON = JSON.stringify(obj); /* In Node.js: fs.writeFileSync('example.json', finalJSON); */ /* Mocked for this example: */ console.log(finalJSON);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在 json 文件中的数组并将其附加到 html 中时遇到问题 - I am having trouble with an array in a json file and appending it into html 我正在尝试从JSON文件中检索数据,但是我无法从特定属性中检索信息 - I am trying to retrieve data from a JSON file, but I am having trouble retrieving information from a specific property 在我的 javascript 中解析 json 文件时遇到问题..但我得到“responseObject.weather[i].weatherresponseObject.weather[i].description” - Having trouble parsing json file in my javascript..but I am getting "responseObject.weather[i].weatherresponseObject.weather[i].description" 我的碰撞代码有问题 - I am having trouble with my collision code 我无法导入此文件 - I am having trouble importing this file 你好。 我在将表单输入写入嵌套的 json 文件时遇到问题 - Hello. I am having trouble writing form input to a nested json file 无法将javascript附加到我的html中 - Having trouble appending javascript into my html 我在为下拉列表解析嵌套的 JSON 数组时遇到问题 - I am having trouble parsing a nested JSON array for a dropdown 我无法从嵌套的 json object 拼接元素 - I am having trouble splicing an element from a nested json object 我在javascript中使用拉斯维加斯幻灯片放映时遇到了麻烦 - I am having trouble with my vegas slideshow in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM