【问题标题】:how to read json embedded ini config file in python如何在python中读取json嵌入的ini配置文件
【发布时间】:2015-07-31 13:08:24
【问题描述】:

我正在使用 python 3.4 我在以格式化方式读取具有 json 格式的配置文件时遇到问题(即不在同一行。) 我的配置文件“Example.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:\Python34\lib\ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "C:\Python34\lib\ast.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.

【问题讨论】:

    标签: python json runtime-error config python-3.4


    【解决方案1】:

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

    您在option 上使用它,这是左侧的名称 ini 文件(在您的示例中为户外、室内和室内 1)。 您想在此选项的右侧 value 上使用它。

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

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

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

    【讨论】:

      【解决方案2】:

      正如您所发现的,这不是有效的 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'}]}}}
      

      【讨论】:

        猜你喜欢
        • 2014-09-17
        • 2020-08-08
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        • 2013-02-14
        相关资源
        最近更新 更多