Coming from a file I have something like the following string:
var1 : data1
var2 : data2
dict1 {
var3 : data3
dict2 {
var4 : data4
}
var5 : data5
}
dict3 {
var6 : data6
var7 : data7
}
and so on. (end of lines are \n, indents are \t each)
And I try to convert it into something like that:
Dictionary={"var1":"data1","var2":"data2", "dict1" :
{"var3":"data3", "dict2" : {
"var4":"data4" }, "var5":"data5"}
, dict3:{"var6":"data6","var7":"data7"}
(indents are only too keep it somehow human readable)
To solve it, all I can think of, is to split it into a list, then walk the list down until I find a "}" in the string, delete it (so i won't run into it later), then walk up until I find string with "{", remove the whitespaces before and the " {" after (using right now temp=re.split ('(\S+) \{',out[z]) for this example the 1st temp[1] would be 'dict2'), add everything in between, and finally move on to the next "}".
But that's not fast or elegant. I am definitely missing something.
code is currently:
def procvar(strinG):
x=y=z=temp1=temp2=0
back = False
out=re.split ('\n',strinG) #left over from some other tries
while z < len(out):
print "z=",z," out[z]= ", out[z]
if "{" in out[z]:
if back == True:
back = False
xtemp=re.split ('(\S+) \{',out[z])
out[z]=xtemp[1]
ytemp=xtemp[1]
temp2=z+1
print "Temp: ",temp1," - ",out[temp1]
out[z]={out[z]:[]}
while temp2 <= temp1:
out[z][xtemp[1]].append(out[temp2]) # not finished here, for the time being I insert the strings as they are
del out[temp2]
temp1-=1
print out[z]
if "}" in out[z]:
back = True
del out[z]
temp1 = z-1
if back == True:
z-=1
else:
z+=1
return out