Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to find a quick way to read a custom "configuration"

I’m trying a find a smooth way to read that file like "json" in python but it’s kinda weird (I tried to convert it but not possible

return {
    ["gradient"] = true,
    ["dark"] = true,
    ["sky"] = false,
    ["rainbow"] = false,
    ["settings"] = {
        ["size"] = 100,
        ["smooth"] = true,
        ["dev"] = {
            ["inspect"] = "F1"
        }
        ["logo_size"] = 600
    },
    ["jokes"] = false,
}

`

tried to make that code but receiving all time errors and not manage to read it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import ast

with open('file.ini') as f:
  data_str = f.read()
  
data_str = data_str.replace('["', '"') .replace('"]', '"').replace("return ", "").replace("=", ":")
                   
data = ast.literal_eval(data_str)

true_values = []

for k, v in data.items():
  if v == True:   
    true_values.append(k)
    
print(true_values)

>Solution :

You can use a recursive function:

def parse(iterator, data):
    # Use a `iterator` to read each line on demand
    while True:
        try:
            line = next(iterator)
        except StopIteration:
            return
        
        line = line.strip()
        line = line.rstrip(',')

        # The end of a dict, end the parsing here
        if line == '}':
            return

        # Ignore lines that aren't key-value pairs
        if ' = ' not in line:
            continue
        
        # Split the key-value pairs into two tokens
        ltoken, rtoken = line.split(' = ')

        # Remove the leading and trailing `["` from the keys
        key = ltoken[2:-2]

        # If it's the start of a nested sub-dictionary,
        if rtoken == '{':
            # Call the function again with the same iterator
            subdata = {}
            parse(iterator, subdata)
            data[key] = subdata

        else:
            # Else, use the same dictionary
            data[key] = rtoken

Usage:

t = """{
    ["gradient"] = true,
    ["dark"] = true,
    ["sky"] = false,
    ["rainbow"] = false,
    ["settings"] = {
        ["size"] = 100,
        ["smooth"] = true,
        ["dev"] = {
            ["inspect"] = "F1"
        }
        ["logo_size"] = 600
    },
    ["jokes"] = false,
}"""

import pprint

data = {}
parse(iter(t.split('\n')), data)
pprint.pprint(data)

It outputs

{'dark': 'true',
 'gradient': 'true',
 'jokes': 'false',
 'rainbow': 'false',
 'settings': {'dev': {'inspect': '"F1"'},
              'logo_size': '600',
              'size': '100',
              'smooth': 'true'},
 'sky': 'false'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading