-2

From there How to check whether the given object is object or Array in JSON string i've found useful to compare if JSON object is array or object

if (json instanceof Array) {
    // get JSON array
} else {
    // get JSON object
}

Problem I have a validator login form and i get messages like:

array('password' => array('isEmpty' => 'Value is required and can't be empty'));

However there is messages like

'Email or password is invalid' , that isn't an array.

Question I need something like this in JavaScript file

if(json hasOnlyOneString)
{
    //do something
} else { || } if(json instaceof Array){
    // do another stuff
}
Community
  • 1
  • 1
I M
  • 61
  • 1
  • 9
  • It would be helpful to supply the actual JSON sent over the network. It looks like your "array" is actually a non-array object. – apsillers Sep 04 '14 at 16:11
  • Here is what appears when i console log error messages https://imageshack.us/i/iduC09Dap – I M Sep 04 '14 at 16:41
  • note, `array('password' => array('isEmpty' => 'Value is required and can't be empty'))` will not be an instance of `Array` in JavaScript.. it also isn't a string, it will simply be an object with a property that contains another object with a property. – Kevin B Sep 04 '14 at 17:47

1 Answers1

1

It sounds like you sometimes get a string when you expect an array or an object. You can check it like this:

var obj = {
 "str": "I am a string",
 "arr": ["I am an array"]
};

obj.str instanceof Array; // -> false
obj.arr instanceof Array; // -> true
typeof obj; // -> object
typeof obj.arr; // -> object (uh-oh! eliminate this possibility by first checking to see if it's an array)

if (obj.str instanceof Array) {
  console.log('do array stuff');
} else {
  if (typeof obj.str === "object") {
    console.log('do object stuff');
  } else {
    console.log('do non-array, non-object, probably string stuff');
  }
}
pherris
  • 17,195
  • 8
  • 42
  • 58
  • this is what i get https://imagizer.imageshack.us/v2/385x127q90/742/Hsmdum.png. Both error messages are considered arrays. – I M Sep 04 '14 at 18:09