如何检查值是否为json对象? [英] How can I check if a value is a json object?

查看:90
本文介绍了如何检查值是否为json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器端代码返回一个值,该值在成功时为json对象,在失败时为字符串'false'.现在如何检查返回的值是否为json对象?

My server side code returns a value which is a json object on success and a string 'false' on failure. Now how can I check whether the returned value is a json object?

推荐答案

jQuery.parseJSON()应该返回类型为"object"的对象(如果字符串是JSON),因此您只需使用typeof检查类型

jQuery.parseJSON() should return an object of type "object", if the string was JSON, so you only have to check the type with typeof

var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
{
  // It is JSON
}
else
{
  if(response ===false)
  {
     // the response was a string "false", parseJSON will convert it to boolean false
  }
  else
  {
    // the response was something else
  }
}

这篇关于如何检查值是否为json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆