2013-05-11 37 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