根据YAML文件-Python3中的用户输入向JSON文件添加自定义字段
我是Python新手。我有一个YAML文件,我用Python文件访问它。在YAML文件中,有字段选项。在YAML文件中,用户可以使用值设置变量。Python文件读取带有值的变量,然后将其添加到JSON文件中。请注意,变量和值可以根据用户进行更改。根据YAML文件-Python3中的用户输入向JSON文件添加自定义字段,python,json,python-3.x,yaml,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"
我怎样才能做到这一点 以下是示例代码:
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"}},
}
如果根目录下的字段True
,则需要输出:
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "b": "kumar", "a": "steven"},
}
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "fields.b": "kumar", "fields.a": "steven"},
}
如果根目录下的字段为假,则需要输出:
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "b": "kumar", "a": "steven"},
}
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "fields.b": "kumar", "fields.a": "steven"},
}
给定一个输入文件:
...
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
False==True
,但最好只测试一个变量为True
包含一个布尔值,如果x:则为x
则为布尔值,如果不是,则为布尔值,如果x:
为True
,因此请使用普通的False
else:
- 不要为输出JSON而烦恼。不需要截断、查找 等等。只需确保您的数据格式正确,然后一次性转储即可。那个 确保您的输出是有效的JSON
- 不要添加注释,说明明显的
#ip
- 在注释标记
后添加一个空格,许多linter抱怨没有该标记#
- 我在上面使用ruamel.yaml(免责声明:我是该软件包的作者),因为
PyYAML程序更新YAML文件会丢失注释信息。
因为
YAML(typ='safe').load()比PyYAML的
(除此之外,PyYAML仅支持过时的YAML 1.1)YAML.load()快
...
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
False==True
,但最好只测试一个变量为True
包含一个布尔值,如果x:则为x
则为布尔值,如果不是,则为布尔值,如果x:
为True
,因此请使用普通的False
else:
- 不要为输出JSON而烦恼。不需要截断、查找 等等。只需确保您的数据格式正确,然后一次性转储即可。那个 确保您的输出是有效的JSON
- 不要添加注释,说明明显的
#ip
- 在注释标记
后添加一个空格,许多linter抱怨没有该标记#
- 我在上面使用ruamel.yaml(免责声明:我是该软件包的作者),因为
PyYAML程序更新YAML文件会丢失注释信息。
因为
YAML(typ='safe').load()比PyYAML的
(除此之外,PyYAML仅支持过时的YAML 1.1)YAML.load()快
locals
我没有在条件字段中添加代码。告诉我一些关于输出的建议。下次,只需编辑您的问题而不是它,然后将内容复制并粘贴到一个新问题中。为什么代码中的条件检查会做同样的事情?还有,为什么要更新locals
我没有在条件字段中添加代码。请告诉我一些输出建议。下次,只需编辑您的问题而不是它,然后将内容复制并粘贴到新问题中。谢谢您的代码。成功了。谢谢你的评论。我会牢记在心,并在将来纠正我的错误。谢谢你的代码。成功了。谢谢你的评论。我会牢记在心,将来改正我的错误。