How to Update an value in json file dynamically


#1

Hi Team,

i have one json file which looks like below

{
“Comment”: “optional comment about the changes in this change batch request”,
“Changes”: [
{
“Action”: “CREATE”,
“ResourceRecordSet”: {
“Name”: “supplier.cloud.com”,
“Type”: “A”,
“TTL”: 300,
“ResourceRecords”: [
{
“Value”: “54.208.201.157
}
]
}
}
]
}

Here my ip address will change dynamically. Now how to update my new ip address in that json file.

(eg) my new ip is 1.2.3.4 i need to update this ip in that 54.208.201.157 place.

Please help me on this


#2

file.json

    ➜  home cat file.json
    {
      "Comment": "optional comment about the changes in this change batch request",
       "Changes": [
	{
		"Action": "CREATE",
		"ResourceRecordSet": {
			"Name": "supplier.cloud.com",
			"Type": "A",
			"TTL": 300,
			"ResourceRecords": [
				{
                                            "Value": "10.0.0.1"
				}
			]
		}
	   }
     ]
   }

script shell

➜  home ./write.sh
Enter the IP:8.8.8.8

the new file.json changed.

 ➜  projects cat file.json
 {
"Comment": "optional comment about the changes in this change batch request",
"Changes": [
	{
		"Action": "CREATE",
		"ResourceRecordSet": {
			"Name": "supplier.cloud.com",
			"Type": "A",
			"TTL": 300,
			"ResourceRecords": [
				{
                                         "Value": "8.8.8.8"
				}
			]
		}
	}
    ]
 }

body of script shell

#!/bin/bash

printf "Enter the IP:"
read IP
if [ -n "$IP" ]; then
    	sed -i -e "s/.*Value.*/\"Value\": \"$IP\"/" file.json
fi

#3

HI luk4z_7

Thanks for your reply the script which you given is working as per my requirement. The only problem is after updating the Value position is changing as below.

{
“Comment”: “optional comment about the changes in this change batch request”,
“Changes”: [
{
“Action”: “CREATE”,
“ResourceRecordSet”: {
“Name”: “diksit.rezopiacloud.com”,
“Type”: “A”,
“TTL”: 300,
“ResourceRecords”: [
{
“Value”: “5.6.8.8”
}
]
}
}
]
}

How to update the value without changing its position


#4

The script was changed to work with tabulation, would that be your question?

#!/bin/bash

printf "Enter the IP:"
read IP

if [ -n "$IP" ]; then
    TAB=$'\t\t\t\t\t\t'
    sed -i '' -e "s/.*Value.*/${TAB}\"Value\": \"$IP\"/g" file.json
fi

#5

SRC=cat file.json |grep -i valu |awk -F: '{print $2 }'
sed -i -e “s/$SRC/ “$IP”/” file.json

Try this


#6

@ luk4z_7

Yes that is my question. Thanks for updating the script with tabulation.

Regards
Arun