简体   繁体   English

使用python从JSON响应中获取特定的键和值?

[英]Take particular Key and values from JSON response using python?

I have a different kind of JSON format.我有一种不同的 JSON 格式。 I am stuck on how to get the 1st Key alone.我被困在如何单独获得第一把钥匙上。

My JSON RESPONSE:我的 JSON 响应:

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.我想单独使用 Name 和 Region 键和值。 Note that root[] will have any number inside so I cant explicitly put the number as it changes every time.请注意, root[] 里面会有任何数字,所以我不能明确地输入数字,因为它每次都会改变。

Python Code Python代码

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"

Pretty simple task if you loop through the dict:如果您遍历 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"])

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:如果要获取与resp对象的特定键相关的值(例如, "root[0]" ),可以使用以下解决方案:

number = 0 # your chosen number (the one inside root)
name = resp[f"root[{number}]"]["Name"]
region = resp[f"root[{number}]"]["region"]

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM