1

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.

Govind Samrow
  • 9,981
  • 13
  • 53
  • 90

4 Answers4

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
Wolfgang
  • 876
  • 5
  • 13
2

try this:

if(typeof json_string == "string"){
   json = JSON.parse(json_string);
}
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69
0

There's not really such thing as a 'JSON object'. Once a JSON string has been successfully decoded it just becomes 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));
Arnauld
  • 5,847
  • 2
  • 15
  • 32
0

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));
suraj.tripathi
  • 417
  • 2
  • 15