-1

I have a file called clients.conf .

Here is its content :

client: {
    # client data
    name: "James"
    information: {
        age: "32"
        adress: "258 Arthur Street"    
    }
    email: jamesbryan@yyyy.com
    certification: {
        status: "expired"
        id: 12345324
    }
}

I would like to parse it using python 2.7 (or 3.x). Here is the code I am using, it doesn't detect any section in the file:

config = ConfigParser()
with open('clients.conf') as stream:
    stream = StringIO(stream.read())  
    config.readfp(stream)

print(config.sections())

The print.sections() at the end provides an empty array.

Nab
  • 133
  • 1
  • 8
  • why not to use `json`? – DecowVR Mar 23 '22 at 19:28
  • 1
    Yeah, `ConfigParser` is meant for INI style files - what you have is nothing like that. Your file has nested blocks and mixed `=`s and `:`s and unquoted string literals and quoted strings and `#` comments..... you'll need to write a parser yourself. – AKX Mar 23 '22 at 19:28
  • 1
    @DecowVR One good reason might be that the input data is not JSON. – AKX Mar 23 '22 at 19:28
  • @AKX `stream.read().replace("\n", ",")` and it will become a json :( (omiting comments) – DecowVR Mar 23 '22 at 19:31
  • 1
    @DecowVR No, no it won't. – AKX Mar 23 '22 at 19:31
  • My bad, the file doesn't contain any "=", I corrected the question. – Nab Mar 23 '22 at 19:32
  • 1
    Where did you get this file? Can you also double-check whether the email field is unquoted as in your example..? – AKX Mar 23 '22 at 19:33
  • Some fields are quoted and some are not :( All I know is that it is a .conf file. I am a beginner to using such files – Nab Mar 23 '22 at 19:34

1 Answers1

1

It looks like an HJSON document, you can parse it using the hjson module.

import hjson

with open("client.conf", 'r') as f:
    conf = hjson.load(f)

print(conf["client"]["name"])  # James
print(conf["client"]["email"])  # jamesbryan@yyyy.com
Cubix48
  • 2,607
  • 2
  • 5
  • 17