I'm trying to see if it's possible to lookup individual keys
out of a JSON
string in Javascript and return it's Value
with Regex
. Sort of like building a JSON
search tool.
Imagine the following JSON
"{
"Name": "Humpty",
"Age": "18",
"Siblings" : ["Dracula", "Snow White", "Merlin"],
"Posts": [
{
"Title": "How I fell",
"Comments": [
{
"User":"Fairy God Mother",
"Comment": "Ha, can't say I didn't see it coming"
}
]
}
]
}"
I want to be able to search through the JSON
string and only pull out individual properties.
lets assume it's a function
already, it would look something like.
function getPropFromJSON(prop, JSONString){
// Obviously this regex will only match Keys that have
// String Values.
var exp = new RegExp("""+prop+"":[^,}]*");
return JSONString.match(exp)[0].replace("""+prop+"":","");
}
It would return the substring of the Value
for the Key
.
e.g.
getPropFromJSON("Comments")
> "[
{
"User":"Fairy God Mother",
"Comment": "Ha, can't say I didn't see it coming"
}
]"
If your wondering why I want to do this instead of using JSON.parse()
, I'm building a JSON document store around localStorage
. localStorage
only supports key/value pairs, so I'm storing a JSON
string of the entire Document
in a unique Key
. I want to be able to run a query on the documents, ideally without the overhead of JSON.parsing()
the entire Collection
of Documents
then recursing over the Keys
/nested Keys
to find a match.
I'm not the best at regex
so I don't know how to do this, or if it's even possible with regex
alone. This is only an experiment to find out if it's possible. Any other ideas as a solution would be appreciated.