0

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"}]}
5
  • 4
    you have if(Array.isArray(data)) intead of if(Array.isArray(json)) Commented Mar 10, 2016 at 22:16
  • What do you mean by single result? It is still array if enclosed in []. You can check length of array and if it equals 1, then you're good to go :) Commented Mar 10, 2016 at 22:23
  • @contrabit thanks for the suggestion. If I use if(Array.isArray(json)) my result goes on sayng both of them are not an array. Commented Mar 10, 2016 at 22:29
  • If those two examples are actually what you consider having an object and an array, I can tell you that both of those are not arrays. Probably you are considering the value of the item property. If you want this to distinguish is that array or not, and you are always sure that you will have this item property, you can test if(Array.isArray(json.item)) Commented Mar 10, 2016 at 22:37
  • Thank you contrabit, you're right. It is indeed the item property. Commented Mar 10, 2016 at 22:47

1 Answer 1

1

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
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, tried the solution and for some reason (data.item) won't work (returns nan) in second case. Used (json.item) and works as expected. Best regards.
Thanks, fixed it. Obviously, It won't work because data is a string

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.