根据来自YAML文件的用户输入将自定义字段添加到JSON文件-Python3

时间:2019-02-18 13:11:44

标签: python json python-3.x yaml

我是Python的新手。我有一个YAML文件,并且正在用Python文件访问它。在YAML文件中,有字段选项。在YAML文件中,用户可以使用值设置变量。 Python文件读取带有值的变量,然后将其添加到JSON文件。请注意,变量和值可以根据用户进行更改。
我怎样才能做到这一点?

这是示例代码:

import yaml
from datetime import datetime
import os
import json

#name for json file
name = "stack.json"

#load data from yml file
data = yaml.safe_load(open('stack.yml'))
data2 = data.get('heartbeat.monitors')

#Current time stamp
timestamp = datetime.now().strftime("%B %d %Y, %H:%M:%S")

#ip
ip ='192.168.1.1'

#getting data from the field and assign it to variable
for item in data2:
    if item["type"] == "icmp":
        fields_under_root = (item["fields_under_root"])

        # if fields_under_root is true,code goes here
        if fields_under_root == True:
            fields = (item["fields"])
            print(fields)
            locals().update(fields)
        #code to be entered

        #if fields_under_root is false, code goes here
        elif fields_under_root == False:
            fields = (item["fields"])
            print(fields)
        #code to be entered
#For writing in JSON File
#Creates a JSON file if not exists
if not os.path.exists(name):
    with open(name, 'w') as f:
        f.write('{}')

#list for storing the values
result = [(timestamp, {'monitor.ip': ip,"fields": fields })]

#For writing in JSON File
with open(name, 'rb+') as f:
    f.seek(-1, os.SEEK_END)
    f.truncate()
    for entry in result:
        _entry = '"{}":{},\n'.format(entry[0], json.dumps(entry[1]))
        _entry = _entry.encode()
        f.write(_entry)
    f.write('}'.encode('ascii'))

在YAML文件中:

heartbeat.monitors:
- type: icmp
  fields:
    a: steven
    b: kumar

  fields_under_root: True

我在JSON文件中的输出:

{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "fields": {"b": "kumar", "a": "steven"}},
}

如果fields_under_rootTrue,则为必需输出:

{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "b": "kumar", "a": "steven"},
}

如果fields_under_rootFalse,则为必需输出:

{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "fields.b": "kumar", "fields.a": "steven"},
}

1 个答案:

答案 0 :(得分:1)

提供输入文件:

...

heartbeat.monitors:
- type: icmp
  fields:
    a: steven
    b: kumar
  # If this option is set to true, the custom fields are stored as top-level
  # fields in the output document instead of being grouped under a fields
  # sub-dictionary. Default is false.
  fields_under_root: True

您的程序应该具有完成所有工作的功能,因此易于测试 通过更新输入文件来更新输入的两个版本。

import ruamel.yaml
from datetime import datetime
import os
import json

# name for json file
json_name = 'stack.json'
yaml_name = 'stack.yaml'


# Current time stamp
timestamp = datetime.now().strftime('%B %d %Y, %H:%M:%S')


def gen_output(data, json_filename):
    ip = '192.168.1.1'
    val = {'monitor.ip': ip}
    result = dict(timestamp=val)

    # getting data from the field and assign it to variable

    for item in data:
        if item['type'] == 'icmp':
            fields = item.pop('fields')
            if item['fields_under_root']:
                val.update(fields)
            else:
                nf = {}
                for k in fields:
                    nf['fields.' + k] = fields[k]
                val.update(nf)

    with open(json_filename, 'w') as fp:
        json.dump(result, fp, ensure_ascii=False)


# load data from YAML file
yaml = ruamel.yaml.YAML(typ='safe')
with open('stack.yaml') as fp:
    data = yaml.load(fp)
data2 = data.get('heartbeat.monitors')

gen_output(data2, json_name)

# show the output file
with open('stack.json') as fp:
    print(fp.read())

print('---------')
# update the YAML input file
with open('stack.yaml') as fp:
    yamlrt = ruamel.yaml.YAML() # default is round-trip, preserving comments
    data = yaml.load(fp)
data['heartbeat.monitors'][0]['fields_under_root'] = False
with open(yaml_name, 'wb') as fp:
    yamlrt.dump(data, fp)

with open('stack.yaml') as fp:
    data = yaml.load(fp)
data2 = data.get('heartbeat.monitors')

gen_output(data2, json_name)
with open('stack.json') as fp:
    print(fp.read())

给出:

{"timestamp": {"monitor.ip": "192.168.1.1", "a": "steven", "b": "kumar"}}
---------
{"timestamp": {"monitor.ip": "192.168.1.1", "fields.a": "steven", "fields.b": "kumar"}}

一般评论:

  • 如果要使用== False== True进行测试,则不要测试is Falseis True,但最好只测试变量{{1} }那 包含一个带有x的布尔值,并且两者都不做,如果不是,则不做布尔值 if x:True,因此请使用普通的False

  • 不必麻烦输出JSON。无需截断,寻找 等等。只需确保您的数据格式正确,然后一次性转储。那 确保您的输出是有效的JSON。

  • 不要添加说明明显的else:

  • 的评论
  • 在注释令牌#ip后面添加一个空格,许多皮棉匠抱怨没有该标记

  • 我在上面使用ruamel.yaml(免责声明:我是该软件包的作者),因为 PyYAML以编程方式更新您的YAML文件将丢失您的评论信息。 而且因为#比PyYAML的YAML(typ='safe').load()更快 (除了PyYAML仅支持过时的YAML 1.1)