Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert String to an Array in JSON file using Shell scripting

Status
Not open for further replies.

vinshas1

Systems Engineer
Nov 27, 2019
1
IN
This is the sample json I have pasted here. I want all the IP address strings to be converted into an array. For example "10.38.32.202" has to be converted to ["10.38.32.202"] everywhere in the JSON. There are multiple IPs in a JSON I am pasting one sample object from the JSON. But the IPs already in an Array should not be altered.

{"network_ip_v4_address": "10.38.32.202","mac_address": "A0:12:34:45","network_ip_v4_address":["10.38.61.1","10.38.32.1"]}
 
Look into a Linux utility called "[tt]jq[/tt]". It can translate between [tt]json[/tt] and several other formats easily (including plain text). It can also query data out of a [tt]json[/tt] format file. Google will get you way more information on how to use it than a few replies here.

 
The example JSON you posted is not valid, because you have duplicate key 'network_ip_v4_address' - e.g. try
Code:
{
  "network_ip_v4_address": "10.38.32.202",
  "mac_address": "A0:12:34:45",
  "network_ip_v4_address": ["10.38.61.1", "10.38.32.1"]
}


If you would provide valid JSON for example like this
Code:
{ 
  "network_ip_v4_address": "10.38.32.202", 
  "mac_address": "A0:12:34:45"
}
you can try this jq command, which puts the ip address into the array:
Code:
$ echo '{"network_ip_v4_address": "10.38.32.202", "mac_address": "A0:12:34:45"}' | jq '. | .network_ip_v4_address = (if (.network_ip_v4_address | type) == "string" then [.network_ip_v4_address] else .network_ip_v4_address end)'
i.e. the output is:
Code:
{
  "network_ip_v4_address": [
    "10.38.32.202"
  ],
  "mac_address": "A0:12:34:45"
}

Trying the same script on JSON where the ip addresses are in the array like
Code:
{
  "network_ip_v4_address": ["10.38.61.1", "10.38.32.1"],
  "mac_address": "A0:12:34:45"
}
lets the array unchanged:
Code:
$ echo '{"network_ip_v4_address": ["10.38.61.1", "10.38.32.1"], "mac_address": "A0:12:34:45"}' | jq '. | .network_ip_v4_address = (if (.network_ip_v4_address | type) == "string" then [.network_ip_v4_address] else .network_ip_v4_address end)'
i.e. the result is:
Code:
{
  "network_ip_v4_address": [
    "10.38.61.1",
    "10.38.32.1"
  ],
  "mac_address": "A0:12:34:45"
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top