JokerMartini
JokerMartini

Reputation: 6147

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/assets/tool_source.cfg"

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

    print data

Upvotes: 1

Views: 68

Answers (2)

vks
vks

Reputation: 67988

You can use re here.

import re
filepath = r"C:/Users/jmartini/Projects/rogue_presetsManager/assets/tool_leveleditormodule_source.cfg"
f=open(filepath, "r")
data = f.read()
print re.findall(r"presets\s*=\s*\{\s*([^}]*?)\s*}", data)

Upvotes: 1

Sandeep Singh Rawat
Sandeep Singh Rawat

Reputation: 1647

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}

Upvotes: 2

Related Questions