我想看看是否可以查找个人keys
出于一个JSON
Javascript 中的字符串并返回它Value
with Regex
。有点像建造一个JSON
搜索工具。
想象一下以下 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"
}
]
}
]
}"
我希望能够通过搜索JSON
字符串并且只提取单个属性。
让我们假设它是一个function
已经,它看起来像这样。
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+"\":","");
}
它将返回的子字符串Value
为了Key
.
e.g.
getPropFromJSON("Comments")
> "[
{
"User":"Fairy God Mother",
"Comment": "Ha, can't say I didn't see it coming"
}
]"
如果您想知道为什么我想这样做而不是使用JSON.parse()
,我正在构建一个 JSON 文档存储localStorage
. localStorage
仅支持键/值对,所以我存储JSON
整个字符串Document
以独特的Key
。我希望能够对文档运行查询,理想情况下没有以下开销JSON.parsing()
整个Collection
of Documents
然后递归Keys
/nested Keys
找到匹配的。
我不是最擅长的regex
所以我不知道该怎么做,或者是否有可能regex
独自的。这只是一个实验,看看是否可行。任何其他想法作为解决方案将不胜感激。