JokerMartini JokerMartini - 4 months ago 11
Python Question

python parse string to get contents between text

How can i collect the text (data) between a set of strings? For example I have this code snippet below, which is a modified version of json, which I don't have the ability to change.

However I want to collect the data between

presets = {...}


{
data = {
friends = {
max = 0 0,
min = 0 0,
},
family = {
cars = {
van = "honda",
car = "ford",
bike = "trek",
},
presets = {
location = "italy",
size = 10,
travelers = False,
},
version = 1,
},
},
}


So my resulting string would be whatever is between the two brackets
{...}
following the word presets. In this case it would be:

location = "italy",
size = 10,
travelers = False,


My starting point so far...

filepath = "C:/Users/jmartini/Projects/rogue_presetsManager/assets/tool_leveleditormodule_source.cfg"

with open(filepath, 'r') as file:
data = file.read().replace('\n', '').replace('\t', '')

print data

Answer

Use PyYaml to get the required data

pip install PyYaml

import yaml
def testjson():
    with open('data.json') as datafile:
        data = datafile.read().replace("\n", "").replace("=", ":")            
        print(yaml.load(data)["data"]["family"]["presets"])

I get this output with your data

{'location': 'italy', 'size': 10, 'travelers': False}
Comments