问题
I am new to gcp and linux. I am trying to get the name from the json
format using the gcloud
command.
Below is the command and output:
gcloud firestore indexes composite list --format=json
Output:
[
{
"fields": [
{
"fieldPath": "is_active",
"order": "ASCENDING"
},
{
"fieldPath": "created_at",
"order": "DESCENDING"
},
{
"fieldPath": "__name__",
"order": "ASCENDING"
}
],
"name": "projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK",
"queryScope": "COLLECTION",
"state": "READY"
}
How can I get the name
value using gcloud command.
I tried using: gcloud firestore indexes composite list | grep name | awk -F'name: ' '{print $2}'
but this didn't give any output.
Please help!
Thanks Pritish
回答1:
Let's assume your tool output doesn't really have an unmatched [
at the start that'd make it invalid JSON as in the example you provided in your question and instead either has both [
and ]
or has neither, i.e. it is valid JSON.
If the output starts with [
and ends with ]
then you'd use jq
as:
gcloud firestore indexes composite list --format=json | jq -r '.[0] .name'
Otherwise you'd use jq
as:
gcloud firestore indexes composite list --format=json | jq -r '.name'
For example, using cat file<N>
in place of gcloud firestore indexes composite list --format=json
which I don't have:
$ cat file1
[
{
"fields": [
{
"fieldPath": "is_active",
"order": "ASCENDING"
},
{
"fieldPath": "created_at",
"order": "DESCENDING"
},
{
"fieldPath": "__name__",
"order": "ASCENDING"
}
],
"name": "projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK",
"queryScope": "COLLECTION",
"state": "READY"
}
]
$
$ cat file1 | jq -r '.[0] .name'
projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK
$ cat file2
{
"fields": [
{
"fieldPath": "is_active",
"order": "ASCENDING"
},
{
"fieldPath": "created_at",
"order": "DESCENDING"
},
{
"fieldPath": "__name__",
"order": "ASCENDING"
}
],
"name": "projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK",
"queryScope": "COLLECTION",
"state": "READY"
}
$
$ cat file2 | jq -r '.name'
projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK
回答2:
Finally, I was able to get the name
value using the below command:
gcloud firestore indexes composite list --format=json | grep '"name"' | awk -F' ' '{print $2}' | awk -F'"' '{print $2}'
Output:
projects/emc-ema-simcs-d-286404/databases/(default)/collectionGroups/customer/indexes/CICAgNjbhowK
来源:https://stackoverflow.com/questions/63921338/how-can-i-extract-only-the-name-field-from-json-by-using-gcloud-command