How to write JSON file using Bash?
Asked Answered
D

2

23

I'd like to write a JSON file using BASH but it seem's not working well..

My code :

sudo echo -e "Name of your app?\n"
sudo read appname
sudo cat "{apps:[{name:\"${appname}\",script:\"./cms/bin/www\",watch:false}]}" > process.json

Issue : -bash: process.json: Permission denied

Discrepant answered 6/10, 2016 at 12:26 Comment(5)
have you checked you have permission to create a file at specified location ?Discriminant
sudo echo and sudo read on the first two lines look completely pointless to meKutenai
When I do sudo vim process.json it works...Discrepant
vim opens the file; with > process.json, the shell opens the file before sudo actually runs.Uncovenanted
Possible duplicate of Output JSON from Bash scriptElope
U
34

Generally speaking, don't do this. Use a tool that already knows how to quote values correctly, like jq:

jq -n --arg appname "$appname" '{apps: [ {name: $appname, script: "./cms/bin/www", watch: false}]}' > process.json

That said, your immediate issues is that sudo only applies the command, not the redirection. One workaround is to use tee to write to the file instead.

echo '{...}' | sudo tee process.json > /dev/null
Uncovenanted answered 6/10, 2016 at 12:29 Comment(2)
Cannot make it an edit because that requires at least 6 characters, but the backtick after false}]} should be replaced with standard tick to work properly: jq -n --arg appname "$appname" '{apps: [ {name: $appname, script: "./cms/bin/www", watch: false}]}' > process.json Element
Thank you, it's fixed now.Uncovenanted
F
12

To output text, use echo rather than cat (which outputs data from files or streams).

Aside from that, you will also have to escape the double-quotes inside your text if you want them to appear in the result.

echo -e "Name of your app?\n"
read appname
echo "{apps:[{name:\"${appname}\",script:\"./cms/bin/www\",watch:false}]}" > process.json

If you need to process more than just a simple line, I second @chepner's suggestion to use a JSON tool such as jq.

Your -bash: process.json: Permission denied comes from the fact you cannot write to the process.json file. If the file does not exist, check that your user has write permissions on the directory. If it exists, check that your user has write permissions on the file.

Firn answered 6/10, 2016 at 12:28 Comment(2)
Is there a tutorial for this?Dovekie
@NoelHarris for what exactly? jq, bash, quoting in bash?Firn

© 2022 - 2024 — McMap. All rights reserved.