2017-03-02 69 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); 
    }); 
    } 

任何善,美的理念是欢迎