0

I want to create dynamic json from response coming from api?? How can i acheive this?? I want to have json as shown below. But i am getting invalid json. What am i doing wrong??

  {
    "data":[
       {
          "dataOverallCount":response.dataOverallCount,
          "dataTotalCount":response.dataTodaysCount
       }
    ],
    "item":[
       {
          "itemOverallCount":response.itemOverallCount,
          "itemTotalCount":response.itemTotalCount
       }
    ]
   
 }

here response is an object as

  {dataOverallCount: 2, dataTodaysCount:0, itemOverallCount:6, itemTotalCount:3}
neelam
  • 119
  • 1
  • 5
  • 14
  • If the API is sending invalid JSON, then the problem is what the API is sending, nothing to be done on client side – Bravo Jul 07 '21 at 04:24
  • Your code is fine, your JSON is valid - it's valid once it resolves. If you take the exact code above and test it, it will show as invalid JSON. But once the variables resolve it's fine. . I ran this all through a snippet and it came out fine. Why do you think it's not valid? – Kinglish Jul 07 '21 at 04:29
  • @Kinglish I want to make it as iterable.. I am assigning it to a variable and then applying ngfor to it but i am getting error as " Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." – neelam Jul 07 '21 at 04:40
  • @Kinglish technically it's not valid JSON as `dataOverallCount` and the other keys aren't wrapped in "". It's a valid JS object and can thus be rendered dynamically in a template/component. The question is lacking clarity as to what exactly is the error they're seeing with displaying/using the response. – Levidps Jul 07 '21 at 04:41
  • @neelam that's b/c `ngFor` only works on arrays. What you've got is an object so if you want to try and do a for loop over it you'd be best to refer to this link: https://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor – Levidps Jul 07 '21 at 04:43
  • @Levidps - I used to think that too, and then I realized JSON validates through linters with integers not quoted. Does that mean validators validate non valid JSON? Truly curious, I don't know the answer – Kinglish Jul 07 '21 at 05:19
  • please post the template code as well or check my answer here: https://stackoverflow.com/a/62382073/5536695 – YogendraR Jul 07 '21 at 06:45
  • @Kinglish numbers valid JSON. I'm talking about the keys. B/c those are strings to be valid JSON they should have quotes wrapping them. – Levidps Jul 07 '21 at 23:27

0 Answers0