【发布时间】:2017-03-14 19:56:24
【问题描述】:
我正在尝试使用 shell 脚本而不使用 jq 来编辑 json 文件。我找到了必要的 python 代码,Python read JSON file and modify,但是当我尝试在 shell 中的一行中执行所有这些代码时,我收到了一个语法错误。 我写了以下命令:
export data = `python -c "import json;import os;filename='test.json';with open(filename, 'r') as f:data = json.load(f) data['id'] = 'abc';os.remove(filename);with open(filename, 'w') as f:json.dump(data, f, indent=4)"`
有什么建议吗?
【问题讨论】:
-
你为什么不把你的代码放在一个单独的python脚本中,你可以在shell中用一行代码调用它? python yourscript.py。你也可以让你的脚本接受你需要的任何参数。
-
为什么不直接创建一个
.py文件并运行它? -
我正在尝试通过 shell 运行 jenkins 作业,我需要其中一个 jenkins 参数,用于修改 json 中的数据。这就是为什么我需要在单个命令中执行修改操作。
-
确保
=周围没有空格。还要考虑$()替换反引号,导致export data=$(python ...) -
我尝试执行:export data=(python -c "import json;import os;filename='test.json';with open(filename, 'r') as f:data = json .load(f) data['id'] = 'abc';os.remove(filename);with open(filename, 'w') as f:json.dump(data, f, indent=4)") 。我在“with”处看到语法错误。