2013-05-11 60 views
2

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

我可以按原样插入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 

想法?

+0

任何'\ t','\ n'在你的json字符串中。也许? – mithunsatheesh 2013-05-11 07:20:58

+0

根据[JSON.parse文档](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)“如果要解析的字符串不是有效的JSON,则会出现SyntaxError异常被抛出。“关于'SyntaxError:Unexpected token o',你似乎知道它是因为'o'char是[object Object]的第一个字符 - 对象默认的字符串表示。尝试'console.log(JSON.parse({“t”:“3”}));'你会得到同样的错误。所以这里似乎解析出错了。 – 2013-05-11 08:33:07

+0

你从哪里得到那个JSON?为什么不用双引号(包括属性和值)引用? – 2013-05-11 08:36:00

回答

1

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

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

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