Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parse data with regular expressions turn into dictionary.

I have a string of data. I would like to turn it into a dictionary

ff = '{wrapper:{one:{now:""},up:"north",down:"south"}}'

Notice that the keys are not text wrappered with ' or ". Can regex help do this? The new text should look like below. If pandas can do this, I could use pandas.

ff = '{"wrapper":{"one":{"now":""},"up":"north","down":"south"}}' 
like image 382
Merlin Avatar asked Apr 03 '26 03:04

Merlin


1 Answers

use a lookaround:

(?<={).*?(?=:)

where

(?<={)    - match { before
.*?       - non greedy
(?=:)    - match : after

So in code it would be..

import re
import json

str = '{wrapper:{one:{now:""},up:"north",down:"south"}}'
str = re.sub('(?<=[{,])(.*?)(?=:)', r'"\1"', str)
jsonobj = json.loads(str)
print jsonobj
like image 78
ergonaut Avatar answered Apr 08 '26 05:04

ergonaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!