Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tell is a string is a stringify'd JSON object

For anyone interested, I ended up building a "localstorage with expirations" script here, http://plugins.jquery.com/project/localcache

What I'm doing: building an extension for Storage, so that the user can do this:

localStorage.setThing(key, value)

and the user can do the following:

localStorage.setThing("key1", 1)
localStorage.setThing("key2", "this is a string")
localStorage.setThing("key3", { prop1: "this is a json obj" })

In my setThing method, I'm checking for the typeof for value, and if typeof value == "object", I'm storing it as localStorage.setItem(key, JSON.stringify(value))

On the getThing method, I know that the value that makes it into localStorage is always going to be a string. So, how can I do this?

var val = localStorage.getItem("key3")
if (val is a previously JSON.stringify'd object) // <-- ??
    return JSON.parse(val)

Do I need to do a regex check on val, and if so, does anyone have a pattern handy which tells me if a string is really a JSON.stringify'd object?

Thanks!

like image 536
Ian Davis Avatar asked Nov 21 '11 00:11

Ian Davis


1 Answers

The usual way to tell if a string is JSON is to run it through a JSON decoder. If it succeeds, it is JSON :-) No need for a regex here.

like image 174
Raymond Hettinger Avatar answered Nov 10 '22 01:11

Raymond Hettinger