【问题标题】:Check if JSON has only one string or is an array检查 JSON 是否只有一个字符串或者是一个数组
【发布时间】:2014-09-05 01:45:35
【问题描述】:

从那里How to check whether the given object is object or Array in JSON string 我发现比较 JSON 对象是数组还是对象很有用

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

问题我有一个验证器登录表单,我收到如下消息:

array('password' => array('isEmpty' => '值为必填项,不能为空'));

但是有类似的消息

'Email or password is invalid' 不是数组。

问题我在 JavaScript 文件中需要这样的东西

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

【问题讨论】:

  • 提供通过网络发送的实际 JSON 会很有帮助。看起来你的“数组”实际上是一个非数组对象。
  • 这是我控制台日志错误消息imageshack.us/i/iduC09Dap时出现的内容@
  • 注意,array('password' => array('isEmpty' => 'Value is required and can't be empty')) 不会是 JavaScript 中 Array 的实例。它也不是字符串,它只是一个具有属性的对象,其中包含另一个具有属性的对象.

标签: javascript json


【解决方案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');
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 2019-05-11
相关资源
最近更新 更多