用于解析单个密钥的正则表达式:Javascript中的JSON值 [英] Regex for parsing single key: values out of JSON in Javascript

查看:136
本文介绍了用于解析单个密钥的正则表达式:Javascript中的JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查看是否可以在Javascript中从 JSON 字符串中查找单个使用正则表达式返回。有点像构建 JSON 搜索工具。

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.

想象一下以下JSON

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"
                }
            ]
        }
    ]
}"

我想要能够搜索 JSON 字符串并仅提取单个属性。

I want to be able to search through the JSON string and only pull out individual properties.

假设它是 function 已经看起来像。

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+"\":","");    
}

它将返回 Value的子串用于

例如

getPropFromJSON("Comments")

> "[
    { 
        "User":"Fairy God Mother",
        "Comment": "Ha, can't say I didn't see it coming"
    }
]"

如果您想知道我为什么要这样做而不是使用 JSON.parse(),我正在 localStorage 周围构建一个JSON文档存储。 localStorage 仅支持键/值对,因此我存储了整个 JSON 字符串>文档在唯一的密钥中。我希望能够对文档运行查询,理想情况下没有 JSON.parsing()的开销整个集合 Documents 然后递归 Keys / nested Keys 找到一个匹配。

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.

我不是最好的正则表达式所以我不知道怎么做这样做,或者甚至可以单独使用 regex 。这只是一个实验,以确定是否可能。任何其他想法作为解决方案将不胜感激。

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.

推荐答案

我强烈反对你这样做。 JSON不是这里明确说明的常用语言: https://cstheory.stackexchange.com / questions / 3987 / is-json-a-regular-language

I would strongly discourage you from doing this. JSON is not a regular language as clearly stated here: 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)&实现一个find函数来遍历结构。

I'd recommend converting your JSON to an object (JSON.parse) & implementing a find function to traverse the structure.

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

Other than that, you can take a look at guts of Douglas Crockford's json2.js parse method. Perhaps an altered version would allow you to search through the JSON string & just return the particular object you were looking for without converting the entire structure to an object. This is only useful if you never retrieve any other data from your JSON. If you do, you might as well have converted the whole thing to begin with.

编辑

为了进一步展示Regex如何分解,这是一个正则表达式尝试解析JSON

Just to further show how Regex breaks down, here's a regex that attempts to parse JSON

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

If you plug it into http://regexpal.com/ with "Dot Matches All" checked. You'll find that it can match some elements nicely like:


正则表达式

"Comments"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\") 

JSON匹配

"Comments": [
                { 
                    "User":"Fairy God Mother",
                    "Comment": "Ha, can't say I didn't see it coming"
                }
            ]

正则表达式

"Name"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")

JSON匹配

"Name": "Humpty"


然而,只要你开始查询具有嵌套数组的Posts这样的更高结构,你就会发现你无法正确返回结构,因为正则表达式没有上下文,其中]是结构的指定结尾。

However as soon as you start querying for the higher structures like "Posts", which has nested arrays, you'll find that you cannot correctly return the structure since the regex does not have context of which "]" is the designated end of the structure.


正则表达式

"Posts"[ :]+((?=\[)\[[^]]*\]|(?=\{)\{[^\}]*\}|\"[^"]*\")

JSON匹配

"Posts": [
  {
      "Title": "How I fell",
      "Comments": [
          { 
              "User":"Fairy God Mother",
              "Comment": "Ha, can't say I didn't see it coming"
          }
      ]


这篇关于用于解析单个密钥的正则表达式:Javascript中的JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆