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

时间:2019-12-04 09:56:47

标签: python json python-3.x

我有另一种JSON格式。我被困在如何独自获得第一把钥匙的问题上。

我的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"
  }
]

} }

我想单独使用Name和Region键和值。请注意,root []内部将有任何数字,因此我无法在每次更改时都明确地输入该数字。

Python代码

test = resp.get('Name')
test2= resp.get('region')
print(test,test2)
##Both prints None

预期:

 "Name": "res1",
 "region": "ca-1",
 "Name": "Demo",
 "region": "ca-1"

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

一种方法是迭代字典。

例如:

for _, v in resp.items():
    print(v['Name'], v['region']) 

输出:

res1 ca-1
Demo ca-1

答案 2 :(得分:1)

如果您遍历字典,则任务非常简单:

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

答案 3 :(得分:1)

给出的粗略方法是您提供的字典:

for k, v in resp.items():
    for kk, vv in v.items():
        if kk == "Name" or kk == "region":
            print(kk, vv)

输出为:

Name res1
region ca-1
Name Demo
region ca-1