【发布时间】:2019-07-11 21:17:05
【问题描述】:
我是 Python 新手。我有一个 YAML 文件,我正在使用 Python 文件访问它。在 YAML 文件中,有 fields 选项。在 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_root 是True,则需要输出:
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "b": "kumar", "a": "steven"},
}
如果fields_under_root 是False,则需要输出:
{"February 18 2019, 17:04:30":{"monitor.ip": "192.168.1.1", "fields.b": "kumar", "fields.a": "steven"},
}
【问题讨论】:
-
为什么代码中的条件检查做同样的事情?还有你为什么要更新
locals -
我没有在条件字段上添加代码。告诉我一些关于输出的建议。
-
下一次,只需编辑您的问题而不是 deleting 它,然后将内容复制并粘贴到一个新问题中。
标签: python json python-3.x yaml