[{"id":"12345","name":"cat"},{"id":"67890","name":"dog"}]
Let's say I have the json array above, I want to use sed/grep to extract the id where I only know the name, for example "dog". I can't use json tool such as jq.
[{"id":"12345","name":"cat"},{"id":"67890","name":"dog"}]
Let's say I have the json array above, I want to use sed/grep to extract the id where I only know the name, for example "dog". I can't use json tool such as jq.
Since the input is json data, I would use jq
for this:
echo '[{"id":"12345","name":"cat"},{"id":"67890","name":"dog"}]' \
| jq --raw-output '.[] | select(.name=="dog") | .id'
If it is not available on servers, install it. An alternative might be to use a programming language like python
, ruby
, perl
, php
.. If you want I can give an example in one of those languages. If they are all not available on your server, then the server installation does not fit your requirements.
As you requested it, here comes a trivial implementation in python
:
import json
data='[{"id":"12345","name":"cat"},{"id":"67890","name":"dog"}]'
for item in json.loads(data):
if item['name'] == "dog":
print(item['id'])
exit(0)
If you want to read from stdin
as in the jq
example use this:
import sys
import json
data=sys.stdin.read()
for item in json.loads(data):
if item['name'] == "dog":
print(item['id'])
exit(0)
(The pythonists might blame me because the code is too verbose, I'm a python noob! ;))
If you want to do this without jq, here is a solution with a mix of sed and grep:
sed 's/},{/}\n{/g' inputfile |grep '"name":"dog"' |sed 's/.*"id":"\([0-9]*\)".*/\1/g
The first part sed 's/},{/}\n{/g' inputfile
put each couple on a separate line.
The second part grep '"name":"dog"'
extracts the line with the id you are looking for (replace dog by the appropriate id)
The third part sed 's/.*"id":"\([0-9]*\)".*/\1/g
extracts the value of id from the line.
Make sure you use gnu version of sed.
Hope that helps!