更新时间:2023-11-30 14:59:40
我不知道这是***的方法(与sed,AWK或Perl相比),但是使用python的方法可以轻松地完成您要的操作json
库.
I don't know if this is the best approach (vs sed, AWK, or Perl) but it is straightforward to do what you're asking using python's json
library.
import json
# read the file as a dict using json.loads
d = json.loads(open('servername.json', 'r').read())
# add your new role to the end of the run_list
d['run_list'].append('role[My_New_Role]')
# write new json to file (specify a new file, or overwrite if you prefer)
open('new_servername.json', 'w').write(json.dumps(d, indent=2))
输出文件如下:
{
"chef_environment": "test",
"name": "myserver123",
"run_list": [
"role[base-pkg]",
"role[interesting_stuff]",
"role[user_apps]",
"role[My_New_Role]"
]
}
很容易将这段代码修改为一个脚本,并以文件名作为输入,这样很容易多次运行.
It's pretty easy to modify this code into a script with the filename as an input so that it's easy to run multiple times.