spedy
spedy

Reputation: 2360

Parsing JSON from text

I'm wondering if this is a good method for parsing JSON out of a string:

json.loads(re.search("({(.+)})", text).group(1))

Can anyone give me an example where this wouldn't work?

Upvotes: 0

Views: 86

Answers (1)

ArtOfWarfare
ArtOfWarfare

Reputation: 21476

You can't find JSON in a string using Regex. Here's a simple way to fail it:

Some text before json {"something": {"inner": 5}, "another": {"yeah": 4}} some text which is after json {}.

Regex can't handle nesting without extensions (which aren't part of the Python standard library). You're using the wrong tool for this job.

It'll either grab too much when it's greedy (seeing a unmatched { or } in the text surrounding the JSON as part of the pattern) or it won't grab enough when it's non-greedy (by using a ?)... it would only match from the first { to the first } if it's non-greedy.

Upvotes: 1

Related Questions