How to say is a string - this is a stringed'd JSON object

For everyone who is interested, I finished creating a "localstorage with expirations" script here, http://plugins.jquery.com/project/localcache

What I am doing: creating 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 check the typeof value for the value, and if typeof value == "object" , I save it as localStorage.setItem(key, JSON.stringify(value))

In the getThing method, I know that the value that makes it in localStorage will always 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 regular expression validation on val, and if so, does anyone have a pattern that tells me if the string is really a JSON.stringify'd object?

Thanks!

+4
source share
3 answers

Another option is to save the object {isJsonObj:true, jsonObj: jsonObj} and check the type - Object, and isJsonObj - true. If any of these is false, then this is not json obj (this means you do not need to understand). I understand this means that you will not always have a string, but it makes it easy to test and will not incur large overheads.

+2
source

The usual way to determine if a string is JSON is to run it through a JSON decoder. If this succeeds, this is JSON :-) There is no need for a regular expression.

+2
source

What speed do you need with this? If this is not a big problem, you can always just try val parsing / decoding, and if that fails, then this is not a JSON object.

+1
source

Source: https://habr.com/ru/post/1382199/


All Articles