0

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"

4 Answers 4

2

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"])
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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"]

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.