'Extract specific key from a json file in kubernetes configmap
I have a k8s config map with json format data. Ex:
apiVersion: v1
kind: ConfigMap
metadata:
name: xyz
namespace: x
data:
resources.json: |
{
"configsets":
[
{
"key1": "value1",
"key2":
[
{
"machine": value,
"id": value
},
{
"machine": value,
"id": value
},
{
"machine": value,
"id": value,
}
]
}
I need the total number of the machines inside key2 as a variable in a bash script. How can I extract this information?
Solution 1:[1]
First of all, the resources.json is wrong and should be something like:
apiVersion: v1
kind: ConfigMap
metadata:
name: xyz
data:
resources.json: |
{
"configsets":
[
{
"key1": "value1",
"key2":
[
{
"machine": "value",
"id": "value"
},
{
"machine": "value",
"id": "value"
},
{
"machine": "value",
"id": "value"
}
]
}
]
}
If so, then you can do:
kubectl get cm xyz -o jsonpath='{.data.resources\.json}' | jq '.configsets[0].key2|keys|length'
that will give you the number of objects inside the array thus the number of machines.
You need to have jq installed. e.g in Ubuntu: sudo apt-get install jq
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dcardozo |
