2017-03-02 70 views
1

在下面的代碼中,我試圖獲得json。但返回的結果中包含括號後一個「空間」開放,前收盤:將字符串轉換爲json失敗的離子2

{ 
    "address": ......, 
    "filename": image.png, 
    "price": 12 
} 

在,如果我用res.json()返回錯誤json parser下面的代碼。相反,如果我使用res.text(),它會完全返回字符串。然後,我試圖通過刪除「」空間替換

this.http.get(Url) 
.map(res => res.text()) 
.subscribe(data => {   
    JSON.stringify(data);   
    console.log(data.price); 
}); 

日誌顯示而不是顯示12

undefined更新當我使用res.json()示休耕錯誤。 enter image description here

+0

'JSON.stringify'轉換'object'到'string'。您正在嘗試選擇'data'的'price'字段,就好像它是'object'一樣。我認爲你的意思是使用'JSON.parse' – echonax

+1

即使你正確使用了JSON.parse(),你發佈的內容也是無效的JSON。不是因爲空格,而是因爲缺少雙引號。 (顯然是'......')。 Fiw後端。使其生成有效的JSON。 –

+0

@echonax'json.parse(data)'還顯示'位置23處的JSON中的意外標記'。 – RSA

回答

1

你JSON是一個對象data,其中包含對象的數組:

{ "data": [{ "address":" استان البرز، کرج، کرج نو، کوچه 102، ایران ", "filename":"image3.png", "distance": 2878 , "price": 101001 }]} 

所以,當你嘗試和控制檯日誌data.price有沒有這樣的事情。如果你真的想CONSOLE.LOG項目的價格是在數組中,你會做到以下幾點:

this.http.get(Url) 
.map(res => res.json().data) // let's extract the array from the JSON 
.subscribe(data => {   
    console.log(data[0].price) // console log the price of the first (and only item) in your array 
}); 
0
在這種情況下,我做了這一串代碼

,當然它也不是那麼的美麗和外觀醜陋。

this.http.get(Url) 
    .map(res => res.text()) 
     .subscribe(data => {    
      console.log(data); 
      this.data=data; 
      //if these two lines removed everything fails again. 
      this.data=this.data.replace(/\n/g,""); 
      this.data=this.data.replace(/\t/g,""); 
      console.log(this.data); 

      //this.data=JSON.stringify(this.data); 
      console.log(this.data); 

      this.data=JSON.parse(this.data); 
      console.log(this.data.data[0].price); 
    }); 
    } 

任何善,美的理念是歡迎