2017-09-01 17 views
1

我從網站解析數據並嘗試更改爲json對象。如何在JSON.stringfy後刪除 n?

這是我的功能:

function outPutJSON() { 

     for (var i = 0; i < movieTitle.length; i++) { 

      var handleN = movieContent[i]; 
      console.log('===\n'); 
      console.log(handleN); 

      data.movie.push({ 
       mpvieTitle: movieTitle[i], 
       movieEnTitle: movieEnTitle[i], 
       theDate: theDate[i], 
       theLength: theLength[i], 
       movieVersion: movieVersion[i], 
       youtubeId: twoId[i], 
       content: movieContent[i] 
      }); 
     }; 

     return JSON.stringify(data); 
    } 

的console.log將打印movieContent [0],如:

enter image description here

但我返回JSON.stringfy(數據); 它會變成: enter image description here

有這麼多/ n我想刪除它。

我試圖改變返回JSON.stringfy(data);這樣:

var allMovieData = JSON.stringify(data); 
allMovieData = allMovieData.replace(/\n/g, ''); 
return allMovieData; 

它不工作的結果是一樣的。

如何刪除/ n當我使用JSON.stringfy()

任何幫助,將不勝感激。提前致謝。

+0

你可以嘗試'.replace(/ \\ N /克, '').replace(/ \\ N /克, '');'?那些實際上可能不是換行符。 – Cerbrus

+0

對不起,它的類型錯誤,我現在解決我的問題。 –

+2

不,我的意思是,在你的數據截圖中,你幾乎可以看到'「\ n」'。所以,試試'.replace(/ \\ n/g,'')'而不是'.replace(/ \ n/g,'')'。 – Cerbrus

回答

1

在你的數據截圖,你從字面上看"\n"

這可能意味着實際的字符串不包含換行符(\n),而是一個轉義的換行符(\\n)。

換行符會被渲染爲換行符。你不會看到\n

要刪除這些,使用.replace(/\\n/g, '')代替.replace(/\n/g, '')

+0

謝謝你的幫助。 –

1

JSON.stringify將新行(\n)和製表符(\t)字符轉換爲字符串,因此,當您嘗試解析它時,字符串將再次包含這些字符串。

所以,你需要搜索字符串\n,你可以這樣做。

const stringWithNewLine = { 
 
    x: `this will conatin 
 
new lines` 
 
}; 
 

 
const json = JSON.stringify(stringWithNewLine); 
 

 
console.log(json.replace(/\\n/g, ''))

+0

謝謝你的好例子。 –