简体   繁体   English

使用Python解析复杂的JSON

[英]Parsing complex JSON with Python

I'm quite new with JSON and Python and trying to work with complex JSON outputs that I'm getting with GET requests. 我对JSON和Python相当陌生,并尝试使用GET请求获得的复杂JSON输出。 This is one example of JSON output (this is a small part of it but the principle is the same): 这是JSON输出的一个示例(这只是其中的一小部分,但原理相同):

{
  "innerSet": [
    {
      "clusterUID": {
        "id": 3585057579401361143
      },
      "rpasState": [
        {
          "rpaUID": {
            "clusterUID": {
              "id": 3585057579401361143
            },
            "rpaNumber": 1
          },
          "status": "OK",
          "repositoryConnectivityStatus": {
            "accessStatus": "OK",
            "multipathingProblems": false
          },
          "remoteRPAsDataLinkStatus": [
            {
              "JsonSubType": "RPAConnectivityStatus",
              "clusterUID": {
                "id": 2671811049708195677
              },
              "entityType": "RPA",
              "connectivityStatus": "OK",
              "rpaUID": {
                "clusterUID": {
                  "id": 2671811049708195677
                },
                "rpaNumber": 1
              }
            }
          ],
         }
      ]
    }
 ]
}

I trying to find the best way to print a single value. 我试图找到打印单个值的最佳方法。 For example, I need the value of "connectivityStatus". 例如,我需要“ connectivityStatus”的值。 Any help will be much appreciated. 任何帮助都感激不尽。

I able to pars simple JSON output. 我能够解析简单的JSON输出。 I have managed to get the entire innerSet tree: 我设法得到整个innerSet树:

x = requests.get('website.com)
d = x.json() print (d['innerSet']) 

However, I'not able to go the lower keys. 但是,我不能移到较低的键。 For example, getting the value for "id" key in "clusterUID": 例如,获取“ clusterUID”中“ id”键的值:

print (d['innerSet']['clusterUID']['id']) 

Results in the following error: TypeError: list indices must be integers, not str 导致以下错误:TypeError:列表索引必须是整数,而不是str

Regards, Yakir. 问候,亚基尔。

You can do this: 你可以这样做:

import simplejson as json
data = json.loads(s)
print data['innerSet'][0]['rpasState'][0]['remoteRPAsDataLinkStatus'][0]['connectivityStatus']

For complex JSON, you can user dpath it's like Xpath but on dict. 对于复杂的JSON,您可以像dpath一样使用dpath ,但要使用dict。

according to your json you could parse it as: 根据您的json,您可以将其解析为:

print(list(dpath.util.search(t, '**/connectivityStatus', yielded=True)))
print(dpath.util.get(t, '/innerSet/0/rpasState/0/remoteRPAsDataLinkStatus/0/connectivityStatus'))

[('innerSet/0/rpasState/0/remoteRPAsDataLinkStatus/0/connectivityStatus', 'OK')]
OK

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

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