2

I did a research and strange enough I couldn't find a proper way of checking if an object is stringifed.

I tried to check like this and assign it but doesn't work(it passes validation and just assigns arr_):

var arr = arr_ instanceof String ? JSON.parse(arr_) : arr_;
showtime
  • 1
  • 1
  • 17
  • 48
  • 2
    `typeof` operator can be used in this case. – Teemu Aug 10 '20 at 10:13
  • @teemu what if it's a string but not a valid stringified object? – B''H Bi'ezras -- Boruch Hashem Aug 10 '20 at 10:19
  • For that you need a try..catch block (see bluejayke's answer), the content of a string is meaningless in any type checking. Notice, that there are stringified objects other than JSON strings, `JSON.parse` can parse only JSON strings. Ex. `JSON.parse('{x: 1})'` fails, though the string contains a stringified valid object. – Teemu Aug 10 '20 at 10:21

1 Answers1

5

Not sure the problem with your code. If the variable arr is meant to be a new array of _arr is a stringified object, then that is the expected behavior.

If you want to make a function that returns a Boolean stating whether a particular string represents a stringified object, then use try and catch

function isStringified(str) { try { return JSON.parse(str); } catch() { return str } }