用于解析单个密钥的正则表达式:Javascript中的JSON值

Ash*_*kes 13 javascript regex json

我想看看是否有可能查找个人keys一出JSON字符串中的Javascript并返回它ValueRegex.有点像构建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"
                }
            ]
        }
    ]
}"
Run Code Online (Sandbox Code Playgroud)

我希望能够搜索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+"\":","");    
}
Run Code Online (Sandbox Code Playgroud)

它将返回Valuefor的子串Key.

例如

getPropFromJSON("Comments")

> "[
    { 
        "User":"Fairy God Mother",
        "Comment": "Ha, can't say I didn't see it coming"
    }
]"
Run Code Online (Sandbox Code Playgroud)

如果您想知道我为什么要这样做而不是使用JSON.parse(),我正在构建一个JSON文档存储localStorage.localStorage只支持键/值对,所以我JSON将整个字符串存储Document在一个唯一的Key.我希望能够对文档运行查询,理想情况下没有JSON.parsing()整个的开销Collection,Documents然后通过Keys/ nested 重复Keys查找匹配.

我不是最好的,regex所以我不知道如何做到这一点,或者甚至可能regex单独做到这一点.这只是一个实验,以确定是否可能.任何其他想法作为解决方案将不胜感激.

Bra*_*one 26

我强烈反对你这样做.JSON不是常用语言,如下所述:https://cstheory.stackexchange.com/questions/3987/is-json-a-regular-language

引用上面的帖子:

例如,考虑一组数组数组:

[ [ [ 1, 2], [2, 3] ] , [ [ 3, 4], [ 4, 5] ] ] 
Run Code Online (Sandbox Code Playgroud)

很明显,你无法使用真正的正则表达式解析它.

我建议将您的JSON转换为对象(JSON.parse)并实现find函数来遍历结构.

除此之外,你可以看看Douglas Crockford的json2.js解析方法.也许更改后的版本将允许您搜索JSON字符串并返回您正在查找的特定对象,而无需将整个结构转换为对象.这仅在您从未从JSON中检索任何其他数据时才有用.如果你这样做,你也可以将整个事情转换为开头.

编辑

为了进一步说明Regex如何分解,这是一个试图解析JSON的正则表达式

如果您将其插入http://regexpal.com/并选中"Dot Matches All".你会发现它可以很好地匹配一些元素:

正则表达式

"Comments"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\") 
Run Code Online (Sandbox Code Playgroud)

JSON匹配

"Comments": [
                { 
                    "User":"Fairy God Mother",
                    "Comment": "Ha, can't say I didn't see it coming"
                }
            ]
Run Code Online (Sandbox Code Playgroud)

正则表达式

"Name"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")
Run Code Online (Sandbox Code Playgroud)

JSON匹配

"Name": "Humpty"
Run Code Online (Sandbox Code Playgroud)

但是,只要您开始查询具有嵌套数组的"Posts"等更高结构,您就会发现无法正确返回结构,因为正则表达式没有上下文,其中"]"是指定的结尾.结构体.

正则表达式

"Posts"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")
Run Code Online (Sandbox Code Playgroud)

JSON匹配

"Posts": [
  {
      "Title": "How I fell",
      "Comments": [
          { 
              "User":"Fairy God Mother",
              "Comment": "Ha, can't say I didn't see it coming"
          }
      ]
Run Code Online (Sandbox Code Playgroud)