Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "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.

like image 614
agnoster Avatar asked Jan 19 '26 16:01

agnoster


2 Answers

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.

like image 71
Seldaek Avatar answered Jan 21 '26 08:01

Seldaek


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.

like image 45
Dave Dopson Avatar answered Jan 21 '26 06:01

Dave Dopson