简体   繁体   English

解析Json提取键值python

[英]Parsing Json extracting key value python

Hi guys I am trying to extract the same key but with different values over a long JSON response, but i keep getting:大家好,我正在尝试在较长的 JSON 响应中提取相同的密钥但具有不同的值,但我不断得到:

KeyError: 'id'

Not sure what i am doing wrong, but i am accessing it using REST API: This is what i have as a script:不知道我做错了什么,但我正在使用 REST API 访问它:这就是我作为脚本的内容:

from requests.auth import HTTPBasicAuth
import requests
import json
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def countries():
    data = requests.get("https://10.24.21.4:8543/api/netim/v1/countries/", verify=False, auth=HTTPBasicAuth("admin", "admin"))
    rep = data.json()
    for cid in rep:
        cid = rep["id"]
        print(cid)
countries()

The response is rather long, but it is like this, you will see "id", and i need the respective values:响应相当长,但就是这样,你会看到“id”,我需要各自的值:

{
    "items": [
        {
            "name": "Afghanistan",
            "displayName": "Afghanistan",
            "meta": {
                "type": "COUNTRY"
            },
            "id": "AF",
            "links": {
                "self": {
                    "path": "/api/netim/v1/countries/AF"
                }
            }
        },
        {
            "name": "Albania",
            "displayName": "Albania",
            "meta": {
                "type": "COUNTRY"
            },
            "id": "AL",
            "links": {
                "self": {
                    "path": "/api/netim/v1/countries/AL"
                }
            }
        },
        {
            "name": "Algeria",
            "displayName": "Algeria",
            "meta": {
                "type": "COUNTRY"
            },
            "id": "DZ",
            "links": {
                "self": {
                    "path": "/api/netim/v1/countries/DZ"
                }
            }
        },
        {
            "name": "American Samoa",
            "displayName": "American Samoa",
            "meta": {
                "type

The response is not an array, it's a dictionary.响应不是数组,而是字典。 You want the "items" element of that dictionary:您想要该字典的“项目”元素:

for cid in rep['items']:

I rewrote your functions a little, You should now be able to get all teh IDs from the JSON response.我稍微重写了你的函数,你现在应该能够从 JSON 响应中获取所有的 ID。 I suggest you look into teh basics of Dictionaries and Lists in Python我建议您在 Python 中查看字典和列表的基础知识

from requests.auth import HTTPBasicAuth
import requests
import json
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def countries():
    data = requests.get("https://10.24.21.4:8543/api/netim/v1/countries/", verify=False, auth=HTTPBasicAuth("admin", "admin"))
    rep = data.json()
    return [elem.get("id","") for elem in rep['items']]

countries()

Update: If you wish to extract the value of the "path" key and simultaneously the value of the "id" key, You would need a list of dictionaries where every dictionary corresponds to a single record from the json.更新:如果您希望提取“path”键的值和“id”键的值,您需要一个字典列表,其中每个字典对应于 json 中的单个记录。

the modified function is as follows:修改后的function如下:

def countries():
    data = requests.get("https://10.24.21.4:8543/api/netim/v1/countries/", verify=False, auth=HTTPBasicAuth("admin", "admin"))
    rep = data.json()
    return [{"id":elem.get("id",""),"path":elem["links"]["self"]["path"]} for elem in rep['items']]

the get() returns a default value in case the key is absent in the dictionary. get()返回一个默认值,以防字典中缺少该键。 The function, new as well as the previous one, would not fail in case the values were not returned in the JSON response for the id and path keys如果id路径键的 JSON 响应中未返回值,则 function 和以前的一样不会失败

If you are sure that the value of links will always be available you can use the above function directly else you will have to write a custom function that would parse the key links and return an empty string if it is empty in the json如果您确定links的值将始终可用,您可以直接使用上面的 function 否则您将不得不编写一个自定义 function 来解析关键links并在 Z466DEEC716ECDF24DCA5436D 中为空时返回一个空字符串

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

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