0

I'm getting Json reponse like this,

var optCities = [{
"resultData": {
"Hoteloption": [
    {   
        "CityRating":"[
        {'City': 'Bangkok','Rating':4.5},
        {'City': 'Phuket','Rating':4.5},
        {'City': 'Nonthaburi','Rating':4.5},
        {'City': 'Broc','Rating':4.5}]"
    }]
}}];

I've tried to create a pipe

transform(value: any, args?: any): any {
    var st = JSON.stringify(value);
    var result =  JSON.parse(st);
    return result;
  }

first tried to create json object. but if I console the result variable it still shows string.

<div *ngFor="let city of optCities[0].resultData.Hoteloption[0].CityRating | strReplace ;let i = index; ">
    {{city.Rating}}
</div>

What I'm missing?

3
  • can you create a plunker ? Commented Aug 2, 2017 at 12:44
  • @RahulSingh I've created jsfiddle its same what i'm trying jsfiddle.net/fmqzxwc3 Commented Aug 2, 2017 at 13:00
  • try this: st.json()['resultData']; Commented Aug 2, 2017 at 14:43

4 Answers 4

2

Your nested object keys should be wrapped in double qoutes instead of single, it is better to fix this from backend, here is some simple solution for do it with JS

Angular pipe

transform(value: any, args?: any): any {
    // i'm guessing that your data (value) is string
    return typeof value==='string' ? JSON.parse(value.replace(/'/g, '"')) : value;
}
Sign up to request clarification or add additional context in comments.

1 Comment

How can I do this in angular2?
1

you are getting incorrect JSON of CityRating Array from server

here is an workaround Define the function in your component

getJson(x){
  let z = x.replace(/'/g, '"');
  return JSON.parse(z);
}

to use in you template

<div *ngFor="let city of 
getJson(optCities[0].resultData.Hoteloption[0].CityRating);let i = 
 index; ">
  {{city.Rating}}
</div>

the function will return you an vaild JSON Array so your loop will work

Comments

0

That's because your JSON object is wrong. Remove the double quotes from the array in CityRating.

var optCities = [{
"resultData": {
"Hoteloption": [
{   
    "CityRating":[
    {'City': 'Bangkok','Rating':4.5},
    {'City': 'Phuket','Rating':4.5},
    {'City': 'Nonthaburi','Rating':4.5},
    {'City': 'Broc','Rating':4.5}]
}]
}}];

2 Comments

that's the problem I can't change that getting it from response of API
any other solution?
0

Not sure, but maube

transform(value: any, args?: any): any {
    return JSON.parse(value);
}

This is if you array really must be in string

1 Comment

Thats not working, getting Unexpected token ' in JSON at position 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.