gpt4 book ai didi

node.js - 我应该在插入到 MongoDB 之前解析 JSON 数据吗?

转载 作者:可可西里 更新时间:2023-11-01 09:52:46 28 4
gpt4 key购买 nike

所以,我从客户端接收一些 JSON 数据到我的 Node.JS 服务器。我想使用 Mongoose 将该 json 插入到我的 MongoDB 实例中。

我可以按原样插入 JSON,效果很好,因为它只是文本。但是,我想在插入之前对其进行解析,这样当我稍后提取它时,它就会非常整洁。

所以,这是可行的:

wordStream.words.push(wordData);

这不是:

wordStream.words.push(JSON.parse(wordData));
  1. 那么,我是否应该在插入之前解析 JSON?

  2. 如果我应该解析 JSON,我该怎么做才能不抛出错误?我需要将所有内容放在双引号“”中,我相信,在它解析之前,但出于某种原因,每当我用双引号创建一个字符串并解析它时,它都会把一切都弄错。

这是 JSON:

      { word: 'bundle',
definitions:
[ { definition: 'A group of objects held together by wrapping or tying.',
partOfSpeech: 'noun' } ],
urlSource: 'testurl',
otherSource: '' }

还有我尝试解析时的错误

/Users/spence450/Documents/development/wordly-dev/wordly-server/node_modules/mongoose/lib/utils.js:409
throw err;
^
SyntaxError: Unexpected token o

想法?

最佳答案

So, should I even want to parse the JSON before insertion?

当您需要在 MongoDB 数据库中进行查询时,将字符串转换为 JSON 对象会对您有所帮助。

And if I should parse the JSON, how do I do it without throwing an error? I need to put everything in double quotes "", I believe, before it will parse, but for some reason whenever I make a string with double quotes and parse it, it turns everything all wrong.

您没有收到 JSON 文档。 JSON 文档必须包含引用的键。

您可以:

  • 使用识别无效 JSON 对象的库(请不要)
  • 使用eval (这是一个安全问题,所以不要这样做)
  • 修复问题根源,创建真正的 JSON 对象。这个不难,看json的特性就知道了here

关于node.js - 我应该在插入到 MongoDB 之前解析 JSON 数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494629/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com