Merlin
Merlin

Reputation: 25649

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"}}' 

Upvotes: 3

Views: 113

Answers (2)

LetzerWille
LetzerWille

Reputation: 5658

(?!") - negative look ahead.

def st_to_dict(st):
    import re
    return re.sub(r'(\b[^:"]+\b)(?!")',r'"\1"',st)

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

print(st_to_dict(ff))

Output:

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

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

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

Upvotes: 4

Related Questions