2014-09-04 12 views
-2

从那里How to check whether the given object is object or Array in JSON string我找到有用的比较,如果JSON对象数组或对象检查JSON只有一个字符串或者是一个数组

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

问题我有一个验证的登录表单,我也得到这样的消息:

array('password'=> array('isEmpty'=>'value is required and can not empty'));

然而有像

消息“电子邮件或密码无效”,即不是一个数组。

问题我需要这样的事情在JavaScript文件

if(json hasOnlyOneString) 
{ 
    //do something 
} else { || } if(json instaceof Array){ 
    // do another stuff 
} 
+0

这将有助于提供通过网络发送的实际JSON。看起来你的“数组”实际上是一个非数组对象。 – apsillers 2014-09-04 16:11:02

+0

这里是当我控制台登录错误消息时出现https://imageshack.us/i/iduC09Dap – user3904245 2014-09-04 16:41:32

+0

请注意,'array('password'=> array('isEmpty'=>'值是必需的,不能为空'))'不会是JavaScript中'Array'的一个实例..它也不是一个字符串,它只是一个带有属性的对象,它包含具有属性的另一个对象。 – 2014-09-04 17:47:00

回答

1

这听起来当你想到一个数组或对象就像你有时会得到一个字符串。你可以这样检查:

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'); 
    } 
} 
+0

这就是我得到的https://imagizer.imageshack.us/v2/385x127q90/742/Hsmdum.png。这两个错误消息都被视为数组。 – user3904245 2014-09-04 18:09:16

+0

我一直在寻找这个。谢谢。 – user3904245 2014-09-04 18:22:48

相关问题