Reputation: 448
I have a different kind of JSON format. I am stuck on how to get the 1st Key alone.
My JSON RESPONSE:
resp={
"root[0]": {
"Name": "res1",
"region": "ca-1",
"tags": [
{
"name": "Environment",
"value": "TC1"
},
{
"name": "Test",
"value": "yes"
}
]
},
"root[3]": {
"Name": "Demo",
"region": "ca-1",
"tags": [
{
"name": "Test1",
"value": "check"
},
{
"name": "Test12",
"value": "yes"
}
]
} }
I want to take the Name and Region key and values alone. Note that root[] will have any number inside so I cant explicitly put the number as it changes every time.
Python Code
test = resp.get('Name')
test2= resp.get('region')
print(test,test2)
##Both prints None
Expected:
"Name": "res1",
"region": "ca-1",
"Name": "Demo",
"region": "ca-1"
Upvotes: 0
Views: 217
Reputation: 1003
a rough approach given resp is your provided dict:
for k, v in resp.items():
for kk, vv in v.items():
if kk == "Name" or kk == "region":
print(kk, vv)
output would be:
Name res1
region ca-1
Name Demo
region ca-1
Upvotes: 1
Reputation: 15364
If you want to obtain the values related to a specific key of your resp
object (for example, "root[0]"
) you can use the following solution:
number = 0 # your chosen number (the one inside root)
name = resp[f"root[{number}]"]["Name"]
region = resp[f"root[{number}]"]["region"]
Upvotes: 1
Reputation: 3890
Pretty simple task if you loop through the dict:
test = {
"root[0]": {
"Name": "res1",
"region": "ca-1",
"tags": [
{
"name": "Environment",
"value": "TC1"
},
{
"name": "Test",
"value": "yes"
}
]
},
"root[3]": {
"Name": "Demo",
"region": "ca-1",
"tags": [
{
"name": "Test1",
"value": "check"
},
{
"name": "Test12",
"value": "yes"
}
]
}}
for k in test:
print(test[k]["Name"])
print(test[k]["region"])
Upvotes: 2
Reputation: 82765
One approach is to iterate the dict.
Ex:
for _, v in resp.items():
print(v['Name'], v['region'])
Output:
res1 ca-1
Demo ca-1
Upvotes: 1