Mia
Mia

Reputation: 448

Take particular Key and values from JSON response using python?

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

Answers (4)

Bharat Kul Ratan
Bharat Kul Ratan

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

Riccardo Bucco
Riccardo Bucco

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

Linh Nguyen
Linh Nguyen

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

Rakesh
Rakesh

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

Related Questions