最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check a variable contains JSON object or string? - Stack Overflow

programmeradmin3浏览0评论

Is it possible to check data in a variable is string or JSON object?

var json_string = '{ "key": 1, "key2": "2" }';

var json_string = { "key": 1, "key2": "2" };

var json_string = "{ 'key': 1, 'key2', 2 }";

When json_string.key2 return 2 or when undefined.

When we need to Use JSON.parse ?

How I check which one is string or JSON object.

Is it possible to check data in a variable is string or JSON object?

var json_string = '{ "key": 1, "key2": "2" }';

var json_string = { "key": 1, "key2": "2" };

var json_string = "{ 'key': 1, 'key2', 2 }";

When json_string.key2 return 2 or when undefined.

When we need to Use JSON.parse ?

How I check which one is string or JSON object.

Share Improve this question edited Aug 1, 2016 at 15:46 Govind Samrow asked Aug 1, 2016 at 15:37 Govind SamrowGovind Samrow 10.2k14 gold badges59 silver badges90 bronze badges 2
  • 1 typeof json_string. – Pranav C Balan Commented Aug 1, 2016 at 15:38
  • Possible duplicate of How can I check if a var is a string in JavaScript? – eclarkso Commented Aug 1, 2016 at 16:42
Add a ment  | 

5 Answers 5

Reset to default 3

because your 3rd json_string is invalid you also have to check for errors:

function checkJSON(json) {
 if (typeof json == 'object')
   return 'object';
 try {
   return (typeof JSON.parse(json));
 }
 catch(e) {
   return 'string';
 }
}

var json_string = '{ "key": 1, "key2": "2" }';
console.log(checkJSON(json_string));    //object

json_string = { "key": 1, "key2": "2" };
console.log(checkJSON(json_string));    //object

json_string = "{ 'key': 1, 'key2', 2 }";
console.log(checkJSON(json_string));    //string

try this:

if(typeof json_string == "string"){
   json = JSON.parse(json_string);
}

There's not really such thing as a 'JSON object'. Once a JSON string has been successfully decoded it just bees an object, or an array, or a primitive (string, number, etc.).

However, you probably want to know whether a string is a valid JSON string:

var string1 = '{ "key": 1, "key2": "2" }';
var string2 = 'Hello World!';
var object = { "key": 1, "key2": "2" };
var number = 123;

function test(data) {
  switch(typeof data) {
    case 'string':
      try {
        JSON.parse(data);
      } catch (e) {
        return "This is a string";
      }
      return "This is a JSON string";

    case 'object':
      return "This is an object";
      
    default:
      return "This is something else";
  }
}

console.log(test(string1));
console.log(test(string2));
console.log(test(object));
console.log(test(number));

To check variable type, you can use typeof operator

And for converting a valid stringified json object, you can use following function

If a variable is object then it does not do anything and returns same object.

but if it is a string then it tries to convert it to object and returns.

  function getJSON(d) {
    var jsonObject;
    jsonObject = d;
    if (typeof d === 'string') {
      try {
        jsonObject = JSON.parse(d);
      } catch (Ex) {
        jsonObject = undefined;
        console.log("d " ,d, 'Error in parsing', Ex);
      }
    }
    return jsonObject;
  };
  var obj = {a:2, b:3};
  var stringified_obj = JSON.stringify(obj);
  console.log(obj);
  console.log(getJSON(stringified_obj));

You can use the constructor property to verify if a variable contains a stringified JSON or an actual JSON object without using try...catch (it looks kinda ugly I think).

const a = {a: 1, b: 2};
const b = "{a: 1, b: 2}";

function IsJsonOrString(obj) {
    if (obj.constructor === ({}).constructor) {
        // obj is a JSON
        return "JSON";
    } else {
        // obj is a String
        return "STRING";
    }
}

console.log(IsJsonOrString(a)); // JSON
console.log(IsJsonOrString(b)); // STRING

Furthermore if you want to verify if the string is a valid parsable JSON string, then you can run JSON.stringify with try...catch but I think you only intend to differentiate between string and json variables.

发布评论

评论列表(0)

  1. 暂无评论