Как извлечь конкретный объект из файла JSON с помощью Python JSON - PullRequest
0 голосов
/ 04 июля 2019

Используя Python, мне нужно извлечь все конечные точки API (только имена конечных точек API) путем чтения из файла JSON.

Ниже приведен пример кода JSON,

{
  "swagger": "2.0",
  "info": {
    "title": "None",
    "description": "some thing over here sample content\n",
    "version": "0.1"
  },
  "produces": [
    "application/json"
  ],
  "basePath": "/busrouting",
  "schemes": [
    "https"
  ],
  "definitions": {
    "OAuth2": {
      "description": "some thing over here sample content\n",
      "type": "coauthor",
      "flow": "implicit",
      "authorization": "NONE",
      "scopes": {
        "Zero": "three",
        "One": "two"
      }
    }
  },
  "paths": {
    "/service-provider/details": {
      "get": {
        "description": "some thing over here sample content",
        "security": [
          {
            "OAuth2": [
              "None",
              "None"
            ]
          }
        ],
        "parameters": [
          {
            "name": "service provider",
            "in": "query",
            "description": "List of service-provider ID's",
            "required": false,
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Record limit. Default is 20",
            "required": false,
            "type": "integer"
          },
          {
            "name": "offset",
            "in": "query",
            "description": "Record offset. Default is 0.",
            "required": false,
            "type": "integer"
          }
        ],
        "tags": [
          "Service Providers"
        ],
        "responses": {
          "200": {
            "description": "OK.",
            "headers": {
              "Link": {
                "description": "some thing over here sample content\n",
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            },
            "schema": {
              "type": "object",
              "properties": {
                "names": {
                  "type": "array",
                  "items": {
                    "$ref": "#/definitions/service-provider"
                  }
                }
              } #Sample add
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Forbidden"
          },
          "404": {
            "description": "Zero"
          },
          "500": {
            "description": "Internal Server Error",
            "schema": {
              "$ref": "#/definitions/Error"
            }
          }
        }
      }
    },
    "/Bus/{bus-id}/names": {
      "get": {
        "description": "some thing over here sample content\n",
        "security": [
          {
            "OAuth2": [
              "None",
              "None"
            ]
          }
        ],
        "parameters": [
          {
            "name": "Bus-id",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "tags": [
          "BusNames"
        ],
        "responses": {
          "200": {
            "description": "OK.",
            "schema": {
              "$ref": "#/definitions/busnames"
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Forbidden"
          },
          "404": {
            "description": "Balances not found"
          },
          "500": {
            "description": "Internal Server Error",
            "schema": {
              "$ref": "#/definitions/Error"
            }
          }
        }
      }
    },
    "/busoperator/{bus-id}/names/routes": {
      "get": {
        "description": "some thing over here sample content.\n",
        "security": [
          {
            "OAuth2": [
              "None",
              "None"
            ]
          }
        ],
        "parameters": [
          {
            "name": "bus-id",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Record limit. Default is 10",
            "required": false,
            "type": "integer"
          },
          {
            "name": "offset",
            "in": "query",
            "description": "Record offset. Default is 0.",
            "required": false,
            "type": "integer"
          }
        ],
        "tags": [
          "bus route mapping"
        ],
        "responses": {
          "200": {
            "description": "Recent Route",
            "headers": {
              "Link": {
                "description": "some thing over here sample content.\n",
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            },
            "schema": {
              "type": "object",
              "properties": {
                "Route details": {
                  "type": "array",
                  "items": {
                    "$ref": "#/definitions/Route"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Not entitled to this account and its transactions"
          },
          "404": {
            "description": "User has no recent transactions"
          },
          "500": {
            "description": "Internal Server Error",
            "schema": {
              "$ref": "#/definitions/Error"
            }
          }
        }
      }
    },
    "/operator/{id}/route/path": {
      "get": {
        "description": "some thing over here sample content.\n",
        "security": [
          {
            "OAuth2": [
              "None",
              "None"
            ]
          }
        ],
        "parameters": [
          {
            "name": "bus-id",
            "in": "path",
            "required": true,
            "type": "string"
          },
          {
            "name": "limit",
            "in": "query",
            "description": "Record limit. Default is 10",
            "required": false,
            "type": "integer"
          },
          {
            "name": "offset",
            "in": "query",
            "description": "Record offset. Default is 0.",
            "required": false,
            "type": "integer"
          }
        ],
        "tags": [
          "Sample Reporting"
        ],
        "responses": {
          "200": {
            "description": "sample actions",
            "headers": {
              "Link": {
                "description": "some thing over here sample content\n",
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            },
            "schema": {
              "type": "object",
              "properties": {
                "Boisterous": {
                  "type": "array",
                  "items": {
                    "$ref": "#/definitions/salesperson"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Not entitled to this account and its transactions"
          },
          "404": {
            "description": "User has no recent transactions"
          },
          "500": {
            "description": "Internal Server Error",
            "schema": {
              "$ref": "#/definitions/Error"
            }
          }
        }
      }
    }
  },
  "definitions": {
    "sample": {
      "required": [
        "demo",
        "request"
      ],
      "description": "Holds identifying attributes for an sample\n",
      "properties": {
        "request": {
          "description": "some thing over here sample content\n",
          "type": "string"
        },
        "sample one": {
          "type": "string"
        },
        "sample two": {
          "type": "string"
        },
        "number": {
          "description": "some thing over here sample content",
          "type": "string"
        },
        "name": {
          "type": "string",
          "description": "some thing over here sample content"
        }
      }
    },
    "dummy": {
      "description": "some thing over here sample content\n",
      "properties": {
        "dummy": {
          "$ref": "#/definitions/samples"
        },
        "data": {
          "type": "string",
          "description": "sample data "
        },
        "country": {
          "type": "string",
          "description": "some thing over here sample content"
        },
        "dataone": {
          "$ref": "#/definitions/samples"
        },
        "error": {
          "$ref": "#/definitions/Error"
        },
        "links": {
          "description": "some thing over here sample content",
          "type": "array",
          "items": {
            "$ref": "#/definitions/Links"
          }
        }
      }
    },
    "reference": {
      "description": "only description\n",
      "properties": {
        "available": {
          "type": "number",
          "format": "double",
          "description": "some thing over here sample content"
        },
        "availableFormatted": {
          "type": "string",
          "description": "some thing over here sample content"
        },
        "held": {
          "type": "number",
          "format": "double",
          "description": "some thing over here sample content."
        },
        "formatted": {
          "type": "string",
          "description": "some thing over here sample content"
        },
        "asst": {
          "type": "string",
          "format": "date-time",
          "description": "Timestamp of , in UTC"
        },
        "sampler": {
          "type": "string",
          "format": "date-time",
          "description": "Timestamp of , in users preferred TZ"
        }
      }
    },
    "dummy": {
      "description": "Transaction done on an account",
      "required": [
        "because",
        "versioned",
        "postdates"
      ],
      "properties": {
        "tintype": {
          "description": "sample content",
          "type": "string"
        },
        "cringed": {
          "description": "some thing over here sample content",
          "type": "string",
          "menu": [
            "D",
            "C"
          ]
        },
        "reference": {
          "description": "Reference information",
          "type": "string"
        },
        "amount": {
          "description": "some thing over here sample content\n",
          "type": "number",
          "format": "double"
        },
        "formatted": {
          "description": "formatted according to user's preferences\n"
        },
        "post Date": {
          "type": "string",
          "format": "date-time",
          "description": "Date-time in UTC"
        },
        "postdate": {
          "type": "string",
          "format": "date-time",
          "description": "Post Date-time in user-preferred TZ"
        },
        "narrative": {
          "type": "string"
        }
      }
    },
    "Links": {
      "description": "Related Links for the resource\n",
      "properties": {
        "rel": {
          "description": "relationship to the resource",
          "type": "string"
        },
        "ref": {
          "description": "URL of the related link",
          "type": "string"
        }
      }
    },
    "Error": { Sample
      "description": "Error descriptor",
      "properties": {
        "code": {
          "type": "integer",
          "format": "intent"
        },
        "message": {
          "type": "string"
        },
        "description": {
          "type": "string"
        },
        "severity": {
          "type": "string"
        },
        "location": {
          "type": "string"
        }
      }
    }
  }
}

Я попробовал следующий код:

import json
with open("example.json", "r") as reading:
        data = json.load(reading)
        print(data["paths"])

Здесь мне нужно пойти дальше кода, чтобы захватить только все имена конечных точек API.

В примере файла json, в разделе «Пути» мне нужно захватить все конечные точки и тип метода API, как показано ниже,

Кроме того, я также хотел бы получить значения для приведенных ниже ключей из примера кода JSON.

В разделе «Параметры» мне также нужно захватить следующие ключи, название: в: требуется:

Ожидаемый результат (только пример):

/service-provider/details
get
bus (comment - refers to the key - name under 'parameters')
query (comment - refers to the key - in under 'parameters')
false (comment - refers to the key - required under 'parameters')

/Bus/{bus-id}/names
get
bus-id (comment - refers to the key - name under 'parameters')
query (comment - refers to the key - in under 'parameters')
false (comment - refers to the key - required under 'parameters')

/busoperator/{bus-id}/names/routes
get
routes (comment - refers to the key - name under 'parameters')
query (comment - refers to the key - in under 'parameters')
false (comment - refers to the key - required under 'parameters')

/operator/{id}/route/path
get
id (comment - refers to the key - name under 'parameters')
query (comment - refers to the key - in under 'parameters')
false (comment - refers to the key - required under 'parameters')

Ответы [ 2 ]

0 голосов
/ 04 июля 2019

Попробуйте это:

with open('example.json', 'r') as f:
    data = json.load(f)
    for path, values in data['paths'].items():
        print(path)
        for value in values:
            print(value)

Это также должно получить все функции конечных точек в пути, если их несколько.

0 голосов
/ 04 июля 2019

Чтобы получить список из двух кортежей (конечная точка, тип), используйте:

[(endpoint, value.keys[0]) for endpoint, value in data["paths"].items()]
...