0

I'm trying to edit a json file using shell scripts without using jq. I found the necessary python code to do so, Python read JSON file and modify, but when I try to execute all of it in a single line in shell, I receive a syntax error. I wrote the following command:

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)"`

Any suggestions?

Community
  • 1
  • 1
wolfsbane
  • 1,729
  • 2
  • 11
  • 17
  • 1
    why don't you just put your code in a separate python script which you can call with a single line in shell? python yourscript.py. You can also have your script take any arguments you would need. – TheoretiCAL Mar 14 '17 at 19:58
  • 1
    Why not just make a `.py` file and run that? – gen_Eric Mar 14 '17 at 19:58
  • i'm trying to run a jenkins job through shell and I need one of the jenkins parameters which will be used to modify the data in the json. That's why I need to perform the modify operation in a single command. – wolfsbane Mar 14 '17 at 20:12
  • Make sure you do not have spaces around `=`. Also consider `$()` replacing the backticks, resulting in `export data=$(python ...)` – Walter A Mar 14 '17 at 23:01
  • I tried to execute: 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)") .I see a syntax error at 'with'. – wolfsbane Mar 15 '17 at 06:53

1 Answers1

0

Got the answer:

$(python -c "import json;import os;filename='test.json';f=open(filename, 'r');data=json.load(f);data['id']="abc";os.remove(filename);f=open(filename, 'w');json.dump(data, f, indent=4);")

Thanks anyway!

wolfsbane
  • 1,729
  • 2
  • 11
  • 17