rish rish - 1 month ago 12x
JSON Question

Read JSON Data With String Key: Angualr2

I am trying to iterate json data in angular2.
If JSON Data is like this

{fileName: "XYZ"}

I am able to iterate using- let data of datas

But If my json data key in string format, how I can iterate in angular2

{"fileName": "XYZ"}


JSON always have double quoted string keys, so these:

{ fileName: "XYZ" }
{ 'fileName': "XYZ" }

Are not valid jsons, but this is:

{ "fileName": "XYZ" }

Javascript objects don't require the keys to be quoted, and if they are then a single quote can be used:

let a = { fileName: "XYZ" };
let b = { 'fileName': "XYZ" };
let c = { "fileName": "XYZ" };

Here a, b and c are equivalent.

In any case, iterating all of those js object is done in the same way:

for (let key in a) {
    console.log(`${ key }: ${ a[key] }`);

Object.keys(b).forEach(key => console.log(`${ key }: ${ b[key] }`));