2

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.

2

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

2

try this:

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

2 Comments

it will only check its a string or not but its not checking JSON .
that would be typeof json_string == "object"
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));

Comments

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));

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.