【问题标题】:How we convert string into json我们如何将字符串转换为 json
【发布时间】:2016-02-04 17:27:25
【问题描述】:

我想将 ansible-init 文件转换为 json。所以,我只使用这段代码: common_shared 文件:

 [sql]
 x.com
 [yps_db]
 y.com
 [ems_db]
 c.com
 [scc_db]
 d.com

 [all:vars]
 server_url="http://x.com/x"
 app_host=abc.com
 server_url="https://x.com"

 [haproxy]
 1.1.1.1    manual_hostname=abc instance_id=i-dddd
 2.2.2.2     manual_hostname=xyz instance_id=i-cccc

用于将 Ansible INI 文件转换为 JSON:

 import json

 options= {} 
 f = open('common_shared')
 x = f.read()
 config_entries = x.split()
 for key,value in zip(config_entries[0::2], config_entries[1::2]):
  cleaned_key = key.replace("[",'').replace("]",'')
  options[cleaned_key]=value

  print json.dumps(options,indent=4,ensure_ascii=False)

但它会打印这个结果:

{
"scc_db": "xxx", 
"haproxy": "x.x.x.x", 
"manual_hostname=xxx": "instance_id=xx", 
"ems_db": "xxx", 
"yps_db": "xxx", 
"all:vars": "yps_server_url=\"xxx\"", 
"1.1.1.5": "manual_hostname=xxx", 
"sql": "xxx", 
"xxx": "scc_server_url=xxxx\""
}

但我想以正确的 JSON 格式打印结果,但无法理解如何操作。我尝试了配置解析器,但没有得到帮助以所需格式打印它。

【问题讨论】:

  • 你没有做任何事情来解析这个文件来转换它。正确的“JSON 格式”究竟是什么?
  • 我更新了我的问题和库存文件格式。请帮忙
  • 感谢您的宝贵意见。但我发现了一些使用 ansible 获取所有库存 json 结果的新方法。我会问到其他发行版

标签: python json


【解决方案1】:

您可以使用ConfigParser 读取您的文件,然后将其转换为要转储的字典。

from ConfigParser import ConfigParser
from collections import defaultdict

config = ConfigParser()
config.readfp(open('/path/to/file.ini'))

def convert_to_dict(config):
    config_dict = defaultdict(dict)
    for section in config.sections():
        for key, value in config.items(section):
            config_dict[section][key] = value

    return config_dict

print convert_to_dict(config)

编辑

正如您在评论中所说,某些订单项只是没有价值的“东西”,以下可能对您有用。

import re
from collections import defaultdict

SECTION_HEADER_RE = re.compile('^\[.*\]$')
KEY_VALUE_RE = re.compile('^.*=.*$')

def convert_ansible_to_dict(filepath_and_name):
    ansible_dict = defaultdict(dict)
    with open(filepath_and_name) as input_file:
        section_header = None
        for line in input_file:
            if SECTION_HEADER_RE.findall(line.strip()):
                section_header = SECTION_HEADER_RE.findall(line.strip())[0]
            elif KEY_VALUE_RE.findall(line.strip()):
                if section_header:
                    # Make sure you have had a header section prior to the line
                    key, value = KEY_VALUE_RE.findall(line.strip())[0].split('=', 1)
                    ansible_dict[section_header][key] = value
            else:
                if line.strip() and section_header:
                    # As they're just attributes without value, assign the value None
                    ansible_dict[section_header][line.strip()] = None

    return ansible_dict

这是一种幼稚的方法,可能无法为您解决所有极端情况,但也许这是朝着正确方向迈出的一步。如果您在第一节标题之前有任何“裸属性”,它们将不会包含在字典中,因为它不知道将其分配到哪里,并且key=value 对的正则表达式正在假设存在将只有 1 行中的等号。我敢肯定,我现在还没有看到很多其他案例,但希望这会有所帮助。

【讨论】:

  • 出现此错误:ConfigParser.ParsingError:文件包含解析错误:
  • 您的配置文件是否只包含节标题,然后是单行信息而不是thing = value 对?
  • 是的,但有些值包含 thing=value,有些包含单行信息
  • 我添加了使用正则表达式逐行解析文件并将项目分配到部分的编辑。希望对您有所帮助。
  • 此错误文件“json_convert.py”,第 21 行,在 convert_ansible_to_dict 键中,value = KEY_VALUE_RE.findall(line.strip())[0].split('=') ValueError: too many要解压的值
【解决方案2】:

Christian 的答案是正确的:使用 ConfigParser。 您对他的解决方案的问题是您的 INI 文件格式不正确。

您需要将所有属性更改为:

键=值
键:值

例如
[sql]
aaaaaaa: 是的

https://wiki.python.org/moin/ConfigParserExamples

https://en.wikipedia.org/wiki/INI_file#Keys_.28properties.29

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多