fran35
fran35

Reputation: 135

js parse json multiple elements vs single

I have some client data that sometines returns a json array and sometimes a single result.

tried:

var json = JSON.parse(data);
if(Array.isArray(data)){
    console.log ("is array");
    //loop
    ..
    //end loop
 } else {
    console.log ("isn't array");
    //process
 } 

But haven't got it working. Even a single json result is being detected as array.

In js, how do I work with it properly?


json looks like:

 {"item":{"clave":"CEL-37","codigo_fabricante":"A2554181"}}

and

{"item":[{"clave":"AC-2972","codigo_fabricante":"EBP-2-003"},{"clave":"SWS-1994","codigo_fabricante":"TMBD-044"}]}

Upvotes: 0

Views: 209

Answers (1)

Mirza Brunjadze
Mirza Brunjadze

Reputation: 544

Both of the json data you provided, are json object, simply because it's enclosed in brackets {}. You have to check for item, not the whole object

var json = JSON.parse(data);
if(Array.isArray(json.item)){
    console.log ("is array");
    //loop
    ..
    //end loop
 } else {
    console.log ("isn't array");
    //process
 }

Upvotes: 1

Related Questions