1

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

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

why do you do a double 'print'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.