Q:

Best way to extract parts of string within square and curly brackets in python

I have a file with rows that have strings like:
{"product_specification"=>[{"key"=>"Pet Type", "value"=>"Dog"}]}
I need to extract {"key"=>"Pet Type", "value"=>"Dog"}.
What would be the best way to extract this, given the curly and square brackets and parentheses present in the string?
When I try to do the following:
row = re.search(r'{"product_specification"=>[([^]}]+)', row).group(1)

I get an error:
unbalanced parenthesis at position 34

If I do
str.replace('{"product_specification"=>[', '')

I get:
replace() takes at least 2 arguments (1 given)

What would be the correct way to do it and what would be better from the point of view of computational time?

A:

You should post more samples, but for the line you posted this regular expression works:
>>> a = '{"product_specification"=>[{"key"=>"Pet Type", "value"=>"Dog"}]}'
>>> import re
>>> re.findall("{[^{}]*?}", a)
['{"key"=>"Pet Type", "value"=>"Dog"}']

If you need the first element you can just use (for example in a function returning the element):
try:
    return re.findall("{[^{}]*?}", a)[0]
except IndexError:
    return None

