开发者

Is there something like Regular Expressions, but for matching JSON instead of strings?

Regular expressions allow us to specify some format a string should match, and then test to see if a string matches, find out where it matches, and capture backreferences.

I'd like to have something like this for JSON. Consider:

{ "title开发者_JS百科": "My blog entry",
  "author": { "name": "Joe", "id": 4324132 },
  "comments: [
    "first!!!",
    "Very insightful!",
    "A++ would read again"
  ]
}

You could match this with something like:

{ "title": (title),
  "author": *,
  "comments": [
    "first!!!",
    ...
  ]
}

(Which would return successful, and bind the capture title to the value "My blog entry")

That's just an example. Would be useful for everything from validating API responses to extracting information from JSON to even (a la RE substitution) transforming JSON.

Anyone seen anything like this? Surprisingly, searching for regexes and JSON in the same context only leads to people trying to parse JSON with regexes. Ew.


There are a few tools that could help you do this, although not exactly with regex's.

First it seems that what you need is validating your data, for that you can use JSON Schema.

Second, to extract the title, assuming you don't want to decode the json string, you can either use JSONPath if you are in JS or PHP, or you could try JsonGrep for CLI or Python. There is also jshon for CLI parsing.


You should check out json:select - it's like CSS-selectors for JSON ... which is as close to a "regex" as you get for dealing with structured data.

If you want to play with it from the command-line, check out underscore-cli, which exposes "select" as one of its commands.


jsonmatch is a library that does the validation part of what you're looking for. It's a bit simpler/lighter-weight than the JSON Schema library referenced in the accepted answer above. If you'd like to extend it to do capturing, pull requests are warmly welcomed ;).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜