如何在 Python 中读取 JSON 嵌入式 INI 配置文件



我正在使用python 3.4,我在以格式化方式(即不在同一行(读取具有json格式的配置文件时遇到问题。我的配置文件"示例.config"是这样的

[ABC]
outdoor = {'GAME':['cricket',
                    'football'],
           'INFO':[
                      {'Players':'eleven',
                       'Fun':'Unlimited'},
                      {'Players':'something',
                       'Fun':'Much_more'}
                     ]
         }
[XYZ]
INDOOR = {'GAME':['Carom'],
           'INFO':[
                        {'Players':'2','Fun':'Less'},
                        {'Players':'4','Fun':'More'}
                      ]
          }
INDOOR1 = {'GAME':['TABLE-TENNIS',
                    'BASKETBALL',
                    'ANYTHING'],
          'INFO':[
                    {'Players':'TWO','Fun':'MORE'},
                    {'Players':'MORE','Fun':'MUCHMORE'}
                     ]
         }

我的代码

config_parser=ConfigParser()
    config_parser.read('Example.config')
    for each_section in config_parser.sections():
        for option in config_parser.options(each_section):
            option=ast.literal_eval(option)
            try:
                games=option['GAME']
                info=option['INFO']
            except:
                print('PLease format config same as qa_config.config file.Please Pay special attention to casing')
                raise
            for game in games:
                for eachInfo in info:
                    _INFO=eachInfo['Players']
                    _FUN=eachInfo['Fun']
                    print (each_section,':n')
                    print ('t',game,':n')
                    print ('t',_INFO,':n')
                    print ('t',_FUN,':n')

错误:

option=ast.literal_eval(option)
  File "C:Python34libast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "C:Python34libast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x02E61910>

如果我将字典作为字符串保存在一行中,而没有在配置文件中进行任何美化,ast.literal_eval()能够处理它。

例如:

outdoor = {'GAME':['cricket','football'],'INFO':[{'Players':'eleven','Fun':'Unlimited'},{'Players':'something','Fun':'Much_more'}]}

所以我想这是由于我在配置文件中使用的选项卡和空格。但是我需要在配置文件中进行美化,因为用户将对其进行更新。

我也尝试过astevaljson.load.T.I.A.

我尝试了您的代码和示例(诚然在 2.7 中(和问题是你在错误的事情上使用ast.literal_eval()

您正在使用它option这是左侧的名称ini 文件(在您的示例中为室外、室内和INDOOR1(。您希望在此选项的右侧上使用它。

将下面缺少的第二行添加到脚本中的相应循环中:

    for option in config_parser.options(each_section):
        option = config_parser.get(each_section, option)
        option = ast.literal_eval(option)

您的多行 ini 文件已完美解析。

正如你所发现的,这不是有效的INI语法。 如果确实需要这种深度结构化的数据,请考虑仅对配置文件使用 YAML,如下所示:

ABC:
  outdoor:
    GAME:
       - cricket
       - football
    INFO:
      - Players: eleven
        Fun: unlimited
      - Players: something
        Fun: much more

并像这样解析:

>>> import yaml
>>> with open('myconfig.yml') as fd:
...   config = yaml.load(fd)

如您所见,它直接解析为 Python 数据结构:

>>> import pprint
>>> pprint.pprint(config)
{'ABC': {'outdoor': {'GAME': ['cricket', 'football'],
                     'INFO': [{'Fun': 'unlimited', 'Players': 'eleven'},
                              {'Fun': 'much more', 'Players': 'something'}]}}}

最新更新