HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Converting JSONP to JSON: Is this Regex correct?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisregexjsonpcorrectjsonconverting

Problem

I'm fetching a string that is JSONP, and looking to convert it to JSON.

I'm using the following regular expression for matching (for removal) the padding on the JSON.

([a-zA-Z_0-9\.]*\()|(\);?$)


In python, here's the line I'm using for converting the JSONP to JSON:

apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp)


Is there anything I should worry about using this regular expression? Any chance I could end up mangling the JSON?

Solution

The problem with the code is that it doesn't really express what you are trying to do:

apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp)


The code would seem to indicate that you are trying to find and replace many instances of some regular expressions inside the string. However, you are really trying to strip parts off of the beginning and end. I'm also not a huge fan of regular expressions because they are usually pretty dense and hard to read. Sometimes they are awesome, but this is not one of those times.

Additionally, you aren't anchoring the regular expression to the beginning of the string which is what you'd need to strip off. The only case I could see that being a problem is perhaps if there were strings inside the json which matched the regular expression. Its best to be sure.

Also, I think JSON-P allows functions like alpha["beta"] which will doesn't fit your regular expression. Also what about additional whitespace or comments?

I would suggest doing something like:

apijson = jsonp[ jsonp.index("(") + 1 : jsonp.rindex(")") ]


That way you are more clearly stripping everything outside of the first and last parenthesis.

Code Snippets

apijson = re.sub(r'([a-zA-Z_0-9\.]*\()|(\);?$)','',jsonp)
apijson = jsonp[ jsonp.index("(") + 1 : jsonp.rindex(")") ]

Context

StackExchange Code Review Q#2561, answer score: 9

Revisions (0)

No revisions yet.