我正在尝试查看是否可以从 Javascript 中的 JSON
字符串中查找单个 key
并返回它的 Value
和 正则表达式
。有点像构建一个 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 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+"\":","");
}
它将返回 Key
的 Value
的子字符串。
例如
getPropFromJSON("Comments")
> "[
{
"User":"Fairy God Mother",
"Comment": "Ha, can't say I didn't see it coming"
}
]"
如果您想知道我为什么要这样做而不是使用 JSON.parse()
,我正在围绕 localStorage
构建一个 JSON 文档存储。 localStorage
仅支持键/值对,因此我将整个 Document
的 JSON
字符串存储在一个唯一的 Key
。我希望能够对文档运行查询,理想情况下没有 JSON.parsing()
Documents
的整个 Collection
的开销然后递归 Keys
/嵌套 Keys
以找到匹配项。
我不是最擅长 regex
的,所以我不知道该怎么做,或者如果单独使用 regex
是否可行。这只是一个实验,看看是否可行。任何其他想法作为解决方案将不胜感激。
最佳答案
我强烈建议您不要这样做。 JSON 不是这里明确说明的常规语言:https://cstheory.stackexchange.com/questions/3987/is-json-a-regular-language
引用上面的帖子:
For example, consider an array of arrays of arrays:
[ [ [ 1, 2], [2, 3] ] , [ [ 3, 4], [ 4, 5] ] ]
Clearly you couldn't parse that with true regular expressions.
我建议将您的 JSON 转换为一个对象 (JSON.parse) 并实现一个查找函数来遍历该结构。
除此之外,您还可以看看 Douglas Crockford 的 json2.js 的内容。解析方法。也许更改后的版本将允许您搜索 JSON 字符串并仅返回您要查找的特定对象,而无需将整个结构转换为对象。这仅在您从不从 JSON 中检索任何其他数据时才有用。如果你这样做了,你还不如一开始就把整个东西都转换了。
编辑
为了进一步展示 Regex 是如何分解的,这里有一个尝试解析 JSON 的正则表达式
如果将其插入 http://regexpal.com/选中“点匹配所有”。你会发现它可以很好地匹配一些元素,比如:
Regex
"Comments"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")
JSON Matched
"Comments": [ { "User":"Fairy God Mother", "Comment": "Ha, can't say I didn't see it coming" } ]
Regex
"Name"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")
JSON Matched
"Name": "Humpty"
但是,一旦您开始查询具有嵌套数组的高级结构(例如“帖子”),您就会发现无法正确返回该结构,因为正则表达式没有指定“]”的上下文结构的结尾。
Regex
"Posts"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")
JSON Matched
"Posts": [ { "Title": "How I fell", "Comments": [ { "User":"Fairy God Mother", "Comment": "Ha, can't say I didn't see it coming" } ]
关于javascript - 用于解析单键 : values out of JSON in Javascript 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8750127/