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


is possible check data in variable 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 need use json.parse ?

how check 1 string or json object.

because 3rd json_string invalid have check 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 

Comments