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

查看:56
本文介绍了如何检查值是否为 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,那么你只需要用 检查类型类型

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天全站免登陆