1

I have a daemon.json file which contains one line as below

{ "insecure-registries":["192.X.X.X:8123"] }

I am trying to use a variable to change generically to the current IP address. In bash script normally I'd store in a variable like

  myip=hostname -I | awk '{print $1}'
 { "insecure-registries":["$myip:8123"] }

How to use a kind of variable in JSON file?

1 Answers1

1

If you have access to jq, I would recommend storing not JSON, but a jq filter, like

{"insecure-registries": ["\($ip):8123"]}

Assume the preceding is in file named foo.jq; then using jq as follows to produce JSON from the filter.

$ myip=$(hostname -I | awk '{print $1}')  # 192.0.2.42, e.g.
$ jq -nf foo.jq --arg ip "$myip"
{
  "insecure-registries": [
    "192.0.2.42:8123"
  ]
}

JSON itself doesn't have a notion of substitution, and bash itself isn't really suitable for making substitutions like this.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Huh. Did you reopen this, or am I mistaken in thinking I'd closed the question as a duplicate? (I don't see any edit history to confirm). – Charles Duffy Apr 10 '20 at 22:03
  • I did reopen; I was half-way through typing this up when you closed it :) I think the duplicate did not quite capture what the OP is looking to do. – chepner Apr 10 '20 at 22:04
  • 1
    Huh. I *do* still consider it duplicative of numerous other "how do I generate JSON from bash?" questions, but... que será, será. – Charles Duffy Apr 10 '20 at 22:05
  • @CharlesDuffy i've checked the Qs you mentioned but is not really the same. I really try to avoid duplication always –  Apr 10 '20 at 22:08
  • @chepner I don't have access to `jq` :/ –  Apr 10 '20 at 22:09
  • @full_steak_developer, if you don't have access to jq, we have several available duplicates that discuss using Python for the same purpose. – Charles Duffy Apr 10 '20 at 22:10
  • As far as i understood it does not solve my issue. File has to be with json extension. –  Apr 10 '20 at 22:15