2017-06-23 87 views
0

我想發送一個JSON字符串,並解析它在我的服務器端節點js。 我想提取具體的值,如標題,但出於某種原因,當我試圖解析它時,我得到了未定義的值。解析節點js中的JSON字符串?

這是我到目前爲止所嘗試的。

Home.ejs

$.each(item, function(key, value) 
      { 
       var s = JSON.stringify(value); 
       s = s.replace(/^\s+|\s+$/g,''); 
       info.push(s); 
      }); 
      console.log("info",info); 

      if (response.status == 'ok') { 
       $.ajax({ 
        type: 'POST', 
        url: '/home', 
        data: JSON.stringify(info), 
        success: function (data) { 


        }, 
        error: function (data) { 
         console.log('error'); 
         console.log(data) 
        } 
       }); 
      } 

這是它在控制檯打印出來。 信息

(20) ["{"title":"Trump ends self-made crisis","pubDate":"…tweet-restricted-super-169.jpg"},"categories":[]}", "{"title":"Intel chiefs: Trump suggested we refute …-mueller-split-4-super-169.jpg"},"categories":[]}", "{"title":"New details emerge in US destroyer colli…ald-damaged-0617-super-169.jpg"},"categories":[]}", "{"title":"Former US government worker charged with…dana-boente-0510-super-169.jpg"},"categories":[]}", "{"title":"Sniper hits ISIS target from over 2 mile…110754-isis-flag-super-169.png"},"categories":[]}", "{"title":"Grenfell Tower blaze: Other London high-…london-fire-0614-super-169.jpg"},"categories":[]}", "{"title":"Prime Minister May offer: EU citizens ca…2344-theresa-may-super-169.jpg"},"categories":[]}", "{"title":"Ousted South Korean president's confidan…outh-korea-court-super-169.jpg"},"categories":[]}", "{"title":"Why neither North Korea nor the United S…k-in-photos-0421-super-169.jpg"},"categories":[]}", "{"title":"Warmbier funeral: 2,500 celebrate kid wh…ier-funeral-0622-super-169.jpg"},"categories":[]}", "{"title":"US, Japan missile interception test fail…issile-launch-02-super-169.jpg"},"categories":[]}", "{"title":"US officials: North Korea tested rocket …ek-in-photo-0519-super-169.jpg"},"categories":[]}", "{"title":"Zuckerberg: Why Facebook's mission chang…-interview-color-super-169.jpg"},"categories":[]}", "{"title":"Fitness model dies after freak kitchen a…burger-instagram-super-169.jpg"},"categories":[]}", "{"title":"Tropical Storm Cindy brings rain, wind t…ig-tbkl-00001316-super-169.jpg"},"categories":[]}", "{"title":"Taliban claim car bomb that killed 30","…an-car-bomb-0622-super-169.jpg"},"categories":[]}", "{"title":"The images Saudi Arabia doesn't want you…war-malnutrition-super-169.jpg"},"categories":[]}", "{"title":"Fact Check: Has Trump created 33,000 min…ig-alee-00003930-super-169.jpg"},"categories":[]}", "{"title":"What do young Indians think of Donald Tr…trump-modi-split-super-169.jpg"},"categories":[]}", "{"title":"Obama blasts Republican health care bill…5-obama-montreal-super-169.jpg"},"categories":[]}"] 
0 
: 
"{"title":"Trump ends self-made crisis","pubDate":"2017-06-22 22:36:00","link":"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html","guid":"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html","author":"","thumbnail":"","description":"President Donald Trump finally, grudgingly, had no choice but to come clean.","content":"President Donald Trump finally, grudgingly, had no choice but to come clean.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622175804-trump-tweet-restricted-super-169.jpg"},"categories":[]}" 
1 
: 
"{"title":"Intel chiefs: Trump suggested we refute Russia collusion","pubDate":"2017-06-22 10:47:14","link":"http://www.cnn.com/collections/intel-intl/","guid":"http://www.cnn.com/collections/intel-intl/","author":"","thumbnail":"","description":"","content":"","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622120332-trump-mueller-split-4-super-169.jpg"},"categories":[]}" 
2 
: 
"{"title":"New details emerge in US destroyer collision investigation","pubDate":"2017-06-22 23:31:38","link":"http://www.cnn.com/2017/06/22/politics/uss-fitzgerald-investigation-update/index.html","guid":"http://www.cnn.com/2017/06/22/politics/uss-fitzgerald-investigation-update/index.html","author":"","thumbnail":"","description":"Five of the seven Navy sailors who died aboard the USS Fitzgerald when it collided with a cargo ship off the east coast of Japan may have been almost instantly \"incapacitated\" and died quickly, according to a very preliminary Navy analysis, a defense official told CNN.","content":"Five of the seven Navy sailors who died aboard the USS Fitzgerald when it collided with a cargo ship off the east coast of Japan may have been almost instantly \"incapacitated\" and died quickly, according to a very preliminary Navy analysis, a defense official told CNN.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170617081911-07-uss-fitzgerald-damaged-0617-super-169.jpg"},"categories":[]}" 
3 
: 
"{"title":"Former US government worker charged with giving top-secret info to China","pubDate":"2017-06-22 23:13:14","link":"http://www.cnn.com/2017/06/22/politics/top-secret-information-china/index.html","guid":"http://www.cnn.com/2017/06/22/politics/top-secret-information-china/index.html","author":"","thumbnail":"","description":"The Justice Department announced Thursday that it had arrested and charged a former US government employee for sharing top-secret information with a Chinese government agent.","content":"The Justice Department announced Thursday that it had arrested and charged a former US government employee for sharing top-secret information with a Chinese government agent.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170510133509-dana-boente-0510-super-169.jpg"},"categories":[]}" 
4 
: 
"{"title":"Sniper hits ISIS target from over 2 miles away","pubDate":"2017-06-23 00:54:32","link":"http://www.cnn.com/2017/06/22/politics/canadian-sniper-record-shot-isis/index.html","guid":"http://www.cnn.com/2017/06/22/politics/canadian-sniper-record-shot-isis/index.html","author":"","thumbnail":"","description":"A Canadian special operations sniper successfully hit an ISIS fighter from a record-breaking distance of more than two miles away while assisting Iraqi forces in the push to retake Mosul, according to Canadian Special Operations Command.","content":"A Canadian special operations sniper successfully hit an ISIS fighter from a record-breaking distance of more than two miles away while assisting Iraqi forces in the push to retake Mosul, according to Canadian Special Operations Command.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/160618110754-isis-flag-super-169.png"},"categories":[]}" 
5 
: 
"{"title":"Grenfell Tower blaze: Other London high-rises 'combustible'","pubDate":"2017-06-23 02:40:44","link":"http://www.cnn.com/2017/06/22/europe/grenfell-tower-fire-theresa-may/index.html","guid":"http://www.cnn.com/2017/06/22/europe/grenfell-tower-fire-theresa-may/index.html","author":"","thumbnail":"","description":"Initial tests on cladding in a number of tower blocks in London have come back as combustible, British Prime Minister Theresa May told the House of Commons Thursday during a statement about last week's fatal Grenfell Tower blaze.","content":"Initial tests on cladding in a number of tower blocks in London have come back as combustible, British Prime Minister Theresa May told the House of Commons Thursday during a statement about last week's fatal Grenfell Tower blaze.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170614142852-45-london-fire-0614-super-169.jpg"},"categories":[]}" 
6 
: 
"{"title":"Prime Minister May offer: EU citizens can stay in UK","pubDate":"2017-06-23 02:06:22","link":"http://www.cnn.com/2017/06/22/europe/theresa-may-brexit-rights/index.html","guid":"http://www.cnn.com/2017/06/22/europe/theresa-may-brexit-rights/index.html","author":"","thumbnail":"","description":"In a Brexit divorce deal offering, British Prime Minister Theresa May on Thursday said European Union citizens would be allowed to stay in the United Kingdom after the country leaves the EU.","content":"In a Brexit divorce deal offering, British Prime Minister Theresa May on Thursday said European Union citizens would be allowed to stay in the United Kingdom after the country leaves the EU.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170620152344-theresa-may-super-169.jpg"},"categories":[]}" 
7 
: 
"{"title":"Ousted South Korean president's confidante sentenced to 3 years","pubDate":"2017-06-23 05:53:19","link":"http://www.cnn.com/2017/06/22/asia/south-korea-choi-soon-sil/index.html","guid":"http://www.cnn.com/2017/06/22/asia/south-korea-choi-soon-sil/index.html","author":"","thumbnail":"","description":"The confidante of former South Korean President Park Geun-hye has been sentenced to three years in prison for soliciting favors for her daughter, a press officer from the Seoul Central District Court told CNN Friday.","content":"The confidante of former South Korean President Park Geun-hye has been sentenced to three years in prison for soliciting favors for her daughter, a press officer from the Seoul Central District Court told CNN Friday.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/161219150546-01-choi-soon-sil-south-korea-court-super-169.jpg"},"categories":[]}" 
8 
: 
"{"title":"Why neither North Korea nor the United States want all-out war","pubDate":"2017-06-23 05:50:20","link":"http://www.cnn.com/2017/06/22/asia/north-korea-war-devastation/index.html","guid":"http://www.cnn.com/2017/06/22/asia/north-korea-war-devastation/index.html","author":"","thumbnail":"","description":"It's been a tense six months on the Korean Peninsula and many North Korea watchers believe the situation is dangerous.","content":"It's been a tense six months on the Korean Peninsula and many North Korea watchers believe the situation is dangerous.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170420182131-05-week-in-photos-0421-super-169.jpg"},"categories":[]}" 
9 
: 
"{"title":"Warmbier funeral: 2,500 celebrate kid who would've 'set the world on fire'","pubDate":"2017-06-22 16:55:31","link":"http://www.cnn.com/collections/intl-warmbier-funeral/","guid":"http://www.cnn.com/collections/intl-warmbier-funeral/","author":"","thumbnail":"","description":"","content":"","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622152959-08-otto-warmbier-funeral-0622-super-169.jpg"},"categories":[]}" 
10 
: 
"{"title":"US, Japan missile interception test fails","pubDate":"2017-06-23 03:05:10","link":"http://www.cnn.com/2017/06/22/politics/us-missile-intercept-test-fails/index.html","guid":"http://www.cnn.com/2017/06/22/politics/us-missile-intercept-test-fails/index.html","author":"","thumbnail":"","description":"A US and Japanese missile test conducted in Hawaii missed its target, but both militaries stopped short of calling it a failure.","content":"A US and Japanese missile test conducted in Hawaii missed its target, but both militaries stopped short of calling it a failure.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170206111347-standard-missile-launch-02-super-169.jpg"},"categories":[]}" 
11 
: 
"{"title":"US officials: North Korea tested rocket engine","pubDate":"2017-06-22 23:31:27","link":"http://www.cnn.com/videos/world/2017/06/22/north-korea-tests-rocket-todd-dnt-tsr.cnn","guid":"http://www.cnn.com/videos/world/2017/06/22/north-korea-tests-rocket-todd-dnt-tsr.cnn","author":"","thumbnail":"","description":"Tensions between the US and North Korea continue to rise after North Korea tested a rocket engine, according to US officials. CNN's Brian Todd reports.","content":"Tensions between the US and North Korea continue to rise after North Korea tested a rocket engine, according to US officials. CNN's Brian Todd reports.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170518180155-09-week-in-photo-0519-super-169.jpg"},"categories":[]}" 
12 
: 
"{"title":"Zuckerberg: Why Facebook's mission changed","pubDate":"2017-06-22 20:06:19","link":"http://money.cnn.com/2017/06/22/technology/facebook-zuckerberg-interview/index.html","guid":"http://money.cnn.com/2017/06/22/technology/facebook-zuckerberg-interview/index.html","author":"","thumbnail":"","description":"","content":"","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622131016-02-zuckerberg-interview-color-super-169.jpg"},"categories":[]}" 
13 
: 
"{"title":"Fitness model dies after freak kitchen accident, family says","pubDate":"2017-06-22 19:15:18","link":"http://www.cnn.com/2017/06/22/world/rebecca-burger-whipped-cream-instagram-fitness-model-death-trnd/index.html","guid":"http://www.cnn.com/2017/06/22/world/rebecca-burger-whipped-cream-instagram-fitness-model-death-trnd/index.html","author":"","thumbnail":"","description":"A popular social media fitness personality died after what can only be described as a freak accident involving a whipped cream canister.","content":"A popular social media fitness personality died after what can only be described as a freak accident involving a whipped cream canister.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622112522-0622-rebecca-burger-instagram-super-169.jpg"},"categories":[]}" 
14 
: 
"{"title":"Tropical Storm Cindy brings rain, wind to Gulf Coast","pubDate":"2017-06-22 22:24:14","link":"http://www.cnn.com/videos/us/2017/06/22/tropical-storm-cindy-orig-tbkl.cnn","guid":"http://www.cnn.com/videos/us/2017/06/22/tropical-storm-cindy-orig-tbkl.cnn","author":"","thumbnail":"","description":"Six million people are under tornado watch in Louisiana, Mississippi and Alabama.","content":"Six million people are under tornado watch in Louisiana, Mississippi and Alabama.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622181943-tropical-storm-cindy-orig-tbkl-00001316-super-169.jpg"},"categories":[]}" 
15 
: 
"{"title":"Taliban claim car bomb that killed 30","pubDate":"2017-06-22 14:28:56","link":"http://www.cnn.com/2017/06/22/asia/afghanistan-car-bomb/index.html","guid":"http://www.cnn.com/2017/06/22/asia/afghanistan-car-bomb/index.html","author":"","thumbnail":"","description":"At least 30 people were killed Thursday in a car bomb attack outside a bank in Lashkar Gah, the capital of Afghanistan's southern Helmand province, officials said.","content":"At least 30 people were killed Thursday in a car bomb attack outside a bank in Lashkar Gah, the capital of Afghanistan's southern Helmand province, officials said.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622071724-01-afghanistan-car-bomb-0622-super-169.jpg"},"categories":[]}" 
16 
: 
"{"title":"The images Saudi Arabia doesn't want you to see","pubDate":"2017-06-22 16:26:56","link":"http://www.cnn.com/2017/06/21/middleeast/yemen-malnutrition-cholera-crisis-images/index.html","guid":"http://www.cnn.com/2017/06/21/middleeast/yemen-malnutrition-cholera-crisis-images/index.html","author":"","thumbnail":"","description":"Batool Ali is six years old, though you would never guess that from her huge, haunted eyes and emaciated frame. Ribs jutting out over her distended belly, Batool weighs less than 16 kilograms (35 pounds). She is one of nearly half a million children in Yemen suffering from severe malnutrition.","content":"Batool Ali is six years old, though you would never guess that from her huge, haunted eyes and emaciated frame. Ribs jutting out over her distended belly, Batool weighs less than 16 kilograms (35 pounds). She is one of nearly half a million children in Yemen suffering from severe malnutrition.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170619144015-12-yemen-civil-war-malnutrition-super-169.jpg"},"categories":[]}" 
17 
: 
"{"title":"Fact Check: Has Trump created 33,000 mining jobs?","pubDate":"2017-06-22 23:59:36","link":"http://www.cnn.com/videos/politics/2017/06/22/fact-check-trump-mining-orig-alee.cnn","guid":"http://www.cnn.com/videos/politics/2017/06/22/fact-check-trump-mining-orig-alee.cnn","author":"","thumbnail":"","description":"CNN's Jake Tapper, in partnership with FactCheck.org, checks a Trump claim that the President added 33,000 mining jobs since his inauguration.","content":"CNN's Jake Tapper, in partnership with FactCheck.org, checks a Trump claim that the President added 33,000 mining jobs since his inauguration.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170622195811-fact-check-trump-mining-orig-alee-00003930-super-169.jpg"},"categories":[]}" 
18 
: 
"{"title":"What do young Indians think of Donald Trump?","pubDate":"2017-06-23 05:02:14","link":"http://www.cnn.com/2017/06/22/asia/young-indians-trump/index.html","guid":"http://www.cnn.com/2017/06/22/asia/young-indians-trump/index.html","author":"","thumbnail":"","description":"Indian Prime Minister Narendra Modi is set to meet US President Donald Trump for the first time on Monday.","content":"Indian Prime Minister Narendra Modi is set to meet US President Donald Trump for the first time on Monday.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170125123753-trump-modi-split-super-169.jpg"},"categories":[]}" 
19 
: 
"{"title":"Obama blasts Republican health care bill","pubDate":"2017-06-23 02:11:50","link":"http://www.cnn.com/2017/06/22/politics/barack-obama-health-care-bill-reaction/index.html","guid":"http://www.cnn.com/2017/06/22/politics/barack-obama-health-care-bill-reaction/index.html","author":"","thumbnail":"","description":"President Barack Obama on Thursday spoke out against a proposed GOP Senate bill that dismantles the Affordable Care Act, also known as Obamacare.","content":"President Barack Obama on Thursday spoke out against a proposed GOP Senate bill that dismantles the Affordable Care Act, also known as Obamacare.","enclosure":{"link":"http://i2.cdn.turner.com/cnnnext/dam/assets/170606215725-obama-montreal-super-169.jpg"},"categories":[]}" 

server.js

app.post("/home",function(req,res) 
{ 

    var data = (req.body); 



    console.log("name",data); 

    var news_title = []; 
    var news_link =[]; 
    var news_date =[]; 
    /*for(var i in req.body){ 

     var item = req.body.items[i]; 
     //console.log(item); 

    }*/ 
    //console.log("name",name); 
}); 

這是它打印出的控制檯

name { '["{\"title\":\"Trump ends self-made crisis\",\"pubDate\":\"2017-06-22 22:36:00\",\"link\":\"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html\",\"guid\":\"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html\",\"author\":\"\",\"thumbnail\":\"\",\"description\":\"President Donald Trump finally, grudgingly, had no choice but to come clean.\",\"content\":\"President Donald Trump finally, grudgingly, had no choice but to come clean.\",\"enclosure\":{\"link\":\"http://i2.cdn.turner.com/cnnnext/dam/assets/170622175804-trump-tweet-restricted-super-169.jpg\"},\"categories\":': [ '' ] } 
name { '["{\"title\":\"Trump ends self-made crisis\",\"pubDate\":\"2017-06-22 22:36:00\",\"link\":\"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html\",\"guid\":\"http://www.cnn.com/2017/06/22/politics/trump-comey-tapes-recordings-white-house/index.html\",\"author\":\"\",\"thumbnail\":\"\",\"description\":\"President Donald Trump finally, grudgingly, had no choice but to come clean.\",\"content\":\"President Donald Trump finally, grudgingly, had no choice but to come clean.\",\"enclosure\":{\"link\":\"http://i2.cdn.turner.com/cnnnext/dam/assets/170622175804-trump-tweet-restricted-super-169.jpg\"},\"categories\":': [ '' ] } 

我想提取標題值,但由於某種原因,我不斷收到未定義當我嘗試req.body.title。

+2

你是否在你的節點應用程序中使用body-parser? –

+0

正如彼得格蘭傑正確發佈帖子,你有一袋芯片,每個芯片也包裝在袋子裏。你打開袋子,拿出一塊芯片和一口 - 這裏只有saran包裝的味道......這是你的「未定義」。不要兩次包裝東西。只要確保你有袋子('JSON.stringify(info)'),但不要包裝單個芯片('JSON.stringify(value)' - >'value')。另外,不要對'JSON.stringify'結果進行'替換' - 'JSON.stringify'已經儘可能的緊湊,沒有什麼好的結果。 – Amadan

回答

0

看起來你有問題,因爲你在每個數組元素上使用JSON.stringify,然後在編譯數組上使用JSON.stringify

您應該通過對整個數組進行字符串化來獲得預期的結果,而不對每個部分進行字符串化。即在你的情況下只是字符串item

   $.ajax({ 
        type: 'POST', 
        url: '/home', 
        data: JSON.stringify(item), 
        success: function (data) { 


        } 
+0

差不多。由於縮進效果不佳,您無法看到它,但是在該程序中,「item」不可用。在循環中執行'info.push(item)'(stringify),然後將'info'字符串化。 – Amadan

+0

如果您只是發送項目數組,您是否需要執行''.each'''循環?這將發送大量消息,數組中的每個項目都有一個消息 –