Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

Tôi đã viết một số mã để lấy dữ liệu từ API Web. Tôi đã có thể phân tích dữ liệu JSON từ API, nhưng kết quả tôi có vẻ khá phức tạp. Đây là một ví dụ:

>>> my_json
{'name': 'ns1:timeSeriesResponseType', 'declaredType': 'org.cuahsi.waterml.TimeSeriesResponseType', 'scope': 'javax.xml.bind.JAXBElement$GlobalScope', 'value': {'queryInfo': {'creationTime': 1349724919000, 'queryURL': 'http://waterservices.usgs.gov/nwis/iv/', 'criteria': {'locationParam': '[ALL:103232434]', 'variableParam': '[00060, 00065]'}, 'note': [{'value': '[ALL:103232434]', 'title': 'filter:sites'}, {'value': '[mode=LATEST, modifiedSince=null]', 'title': 'filter:timeRange'}, {'value': 'sdas01', 'title': 'server'}]}}, 'nil': False, 'globalScope': True, 'typeSubstituted': False}

Nhìn qua dữ liệu này, tôi có thể thấy dữ liệu cụ thể mà tôi muốn: giá trị

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
0 được dán nhãn là
>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
1.

Làm thế nào tôi có thể viết mã trực tiếp nhận được giá trị này?

Tôi không cần bất kỳ logic tìm kiếm nào để tìm giá trị này. Tôi có thể thấy những gì tôi cần khi nhìn vào phản hồi; Tôi chỉ cần biết làm thế nào để dịch nó thành mã cụ thể để trích xuất giá trị cụ thể, theo một cách được mã hóa cứng. Tôi đã đọc một số hướng dẫn, vì vậy tôi hiểu rằng tôi cần sử dụng

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
2 để truy cập các yếu tố của danh sách và từ điển lồng nhau; Nhưng tôi không thể tìm ra chính xác cách nó hoạt động cho một trường hợp phức tạp.

Tổng quát hơn, làm thế nào tôi có thể tìm ra "đường dẫn" là gì cho dữ liệu và viết mã cho nó?

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

Hỏi ngày 8 tháng 10 năm 2012 lúc 19:30Oct 8, 2012 at 19:30

4

Để tham khảo, hãy xem JSON ban đầu sẽ trông như thế nào, với định dạng khá:

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}

Điều đó cho phép chúng tôi thấy cấu trúc của dữ liệu rõ ràng hơn.

Trong trường hợp cụ thể, trước tiên chúng tôi muốn xem xét giá trị tương ứng theo khóa

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
3 trong dữ liệu phân tích cú pháp của chúng tôi. Đó là một mệnh lệnh khác; Chúng ta có thể truy cập giá trị của khóa
>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
4 của nó theo cùng một cách và tương tự
>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
1 từ đó.

Để có được giá trị mong muốn, chúng tôi chỉ cần đặt những quyền truy cập đó lần lượt:

my_json['value']['queryInfo']['creationTime'] # 1349724919000

Karl Knechtel

59.4K10 Huy hiệu vàng86 Huy hiệu bạc132 Huy hiệu đồng10 gold badges86 silver badges132 bronze badges

Đã trả lời ngày 8 tháng 10 năm 2012 lúc 19:35Oct 8, 2012 at 19:35

dm03514dm03514dm03514

53.5K18 Huy hiệu vàng104 Huy hiệu bạc142 Huy hiệu đồng18 gold badges104 silver badges142 bronze badges

1

Tôi chỉ cần biết làm thế nào để dịch nó thành mã cụ thể để trích xuất giá trị cụ thể, theo một cách được mã hóa cứng.

Nếu bạn truy cập lại API, dữ liệu mới có thể không khớp với kỳ vọng của mã. Bạn có thể thấy hữu ích để thêm một số xử lý lỗi. Ví dụ: sử dụng

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
6 để truy cập từ điển trong dữ liệu, thay vì lập chỉ mục:

name = my_json.get('name') # will return None if 'name' doesn't exist

Một cách khác là kiểm tra rõ ràng một cách rõ ràng:

if 'name' in resp_dict:
    name = resp_dict['name']
else:
    pass

Tuy nhiên, các phương pháp này có thể thất bại nếu cần tiếp cận thêm. Kết quả giữ chỗ của

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
7 không phải là một từ điển hay danh sách, vì vậy cố gắng truy cập nó theo cách đó sẽ thất bại trở lại (với
>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
8). Vì "đơn giản là tốt hơn phức tạp" và "dễ dàng yêu cầu tha thứ hơn sự cho phép", giải pháp đơn giản là sử dụng xử lý ngoại lệ:

try:
    creation_time = my_json['value']['queryInfo']['creationTime']
except (TypeError, KeyError):
    print("could not read the creation time!")
    # or substitute a placeholder, or raise a new exception, etc.

Karl Knechtel

59.4K10 Huy hiệu vàng86 Huy hiệu bạc132 Huy hiệu đồng10 gold badges86 silver badges132 bronze badges

Đã trả lời ngày 8 tháng 10 năm 2012 lúc 19:35Aug 17, 2015 at 20:49

53.5K18 Huy hiệu vàng104 Huy hiệu bạc142 Huy hiệu đồngButtersB

Tôi chỉ cần biết làm thế nào để dịch nó thành mã cụ thể để trích xuất giá trị cụ thể, theo một cách được mã hóa cứng.1 gold badge7 silver badges13 bronze badges

0

Nếu bạn truy cập lại API, dữ liệu mới có thể không khớp với kỳ vọng của mã. Bạn có thể thấy hữu ích để thêm một số xử lý lỗi. Ví dụ: sử dụng

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
6 để truy cập từ điển trong dữ liệu, thay vì lập chỉ mục:

import json

# load the data into an element
data={"test1": "1", "test2": "2", "test3": "3"}

# dumps the json object into an element
json_str = json.dumps(data)

# load the json to a string
resp = json.loads(json_str)

# print the resp
print(resp)

# extract an element in the response
print(resp['test1'])

Karl Knechtel

59.4K10 Huy hiệu vàng86 Huy hiệu bạc132 Huy hiệu đồng10 gold badges86 silver badges132 bronze badges

Đã trả lời ngày 8 tháng 10 năm 2012 lúc 19:35Feb 19, 2016 at 16:27

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

1

53.5K18 Huy hiệu vàng104 Huy hiệu bạc142 Huy hiệu đồng

Tôi chỉ cần biết làm thế nào để dịch nó thành mã cụ thể để trích xuất giá trị cụ thể, theo một cách được mã hóa cứng.statecode from the COVID API (a JSON array).

import requests

r = requests.get('https://api.covid19india.org/data.json')

x = r.json()['statewise']

for i in x:
  print(i['statecode'])

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

Nếu bạn truy cập lại API, dữ liệu mới có thể không khớp với kỳ vọng của mã. Bạn có thể thấy hữu ích để thêm một số xử lý lỗi. Ví dụ: sử dụng

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
6 để truy cập từ điển trong dữ liệu, thay vì lập chỉ mục:Apr 14, 2021 at 12:43

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

2

Một cách khác là kiểm tra rõ ràng một cách rõ ràng:

from functools import reduce
import re


def deep_get_imps(data, key: str):
    split_keys = re.split("[\\[\\]]", key)
    out_data = data
    for split_key in split_keys:
        if split_key == "":
            return out_data
        elif isinstance(out_data, dict):
            out_data = out_data.get(split_key)
        elif isinstance(out_data, list):
            try:
                sub = int(split_key)
            except ValueError:
                return None
            else:
                length = len(out_data)
                out_data = out_data[sub] if -length <= sub < length else None
        else:
            return None
    return out_data


def deep_get(dictionary, keys):
    return reduce(deep_get_imps, keys.split("."), dictionary)

Tuy nhiên, các phương pháp này có thể thất bại nếu cần tiếp cận thêm. Kết quả giữ chỗ của

>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
7 không phải là một từ điển hay danh sách, vì vậy cố gắng truy cập nó theo cách đó sẽ thất bại trở lại (với
>>> print(json.dumps(my_json, indent=4))
{
    "name": "ns1:timeSeriesResponseType",
    "declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
    "scope": "javax.xml.bind.JAXBElement$GlobalScope",
    "value": {
        "queryInfo": {
            "creationTime": 1349724919000,
            "queryURL": "http://waterservices.usgs.gov/nwis/iv/",
            "criteria": {
                "locationParam": "[ALL:103232434]",
                "variableParam": "[00060, 00065]"
            },
            "note": [
                {
                    "value": "[ALL:103232434]",
                    "title": "filter:sites"
                },
                {
                    "value": "[mode=LATEST, modifiedSince=null]",
                    "title": "filter:timeRange"
                },
                {
                    "value": "sdas01",
                    "title": "server"
                }
            ]
        }
    },
    "nil": false,
    "globalScope": true,
    "typeSubstituted": false
}
8). Vì "đơn giản là tốt hơn phức tạp" và "dễ dàng yêu cầu tha thứ hơn sự cho phép", giải pháp đơn giản là sử dụng xử lý ngoại lệ:

res = {
    "status": 200,
    "info": {
        "name": "Test",
        "date": "2021-06-12"
    },
    "result": [{
        "name": "test1",
        "value": 2.5
    }, {
        "name": "test2",
        "value": 1.9
    },{
        "name": "test1",
        "value": 3.1
    }]
}

>>> deep_get(res, "info")
{'name': 'Test', 'date': '2021-06-12'}
>>> deep_get(res, "info.date")
'2021-06-12'
>>> deep_get(res, "result")
[{'name': 'test1', 'value': 2.5}, {'name': 'test2', 'value': 1.9}, {'name': 'test1', 'value': 3.1}]
>>> deep_get(res, "result[2]")
{'name': 'test1', 'value': 3.1}
>>> deep_get(res, "result[-1]")
{'name': 'test1', 'value': 3.1}
>>> deep_get(res, "result[2].name")
'test1'

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

azec-pdx

Đã trả lời ngày 17 tháng 8 năm 2015 lúc 20:496 gold badges54 silver badges86 bronze badges

ButtersbbuttersbJun 11, 2021 at 15:29

Hướng dẫn python extract data from json response - python trích xuất dữ liệu từ phản hồi json

1

Làm thế nào trích xuất dữ liệu cụ thể từ JSON Python?

Làm thế nào để bạn gọi dữ liệu JSON trong Python ?..
Tạo một tệp python mới một json nhập ..
Crate một từ điển dưới dạng một chuỗi để sử dụng làm json ..
Sử dụng mô -đun JSON để chuyển đổi chuỗi của bạn thành từ điển ..
Viết một lớp để tải dữ liệu từ chuỗi của bạn ..
Khởi tạo một đối tượng từ lớp của bạn và in một số dữ liệu từ nó ..

Làm thế nào trích xuất dữ liệu JSON từ phản hồi?

Cách trích xuất dữ liệu từ cơ thể phản hồi (JSON & XML) trong Postman..
Bước 1: Thêm yêu cầu trong Postman. ....
Bước 2: Phân tích dữ liệu từ phản hồi JSON. ....
Bước 3: Trích xuất đường dẫn của nút mong muốn từ mảng JSON lồng nhau. ....
Bước 4: Sử dụng đường dẫn để trích xuất dữ liệu từ cơ thể phản hồi. ....
Bước 1: Thêm yêu cầu trong Postman ..

Làm thế nào để bạn trích xuất một giá trị duy nhất từ phản hồi JSON trong Python?

Chương trình Python để trích xuất một giá trị duy nhất từ phản hồi JSON (sử dụng cuộc gọi API)..
Khai báo base_url với biến khóa API ..
Lấy các đầu vào từ người dùng ..
Thêm đầu vào của người dùng vào base_url của chúng tôi và thực hiện final_url hoặc thực hiện yêu cầu API vào máy chủ và tìm nạp dữ liệu từ máy chủ ..

Làm thế nào để bạn đọc một phản hồi JSON trong Python?

Để đọc phản hồi JSON, có một thư viện được sử dụng rộng rãi có tên là Urllib trong Python.Thư viện này giúp mở URL và đọc phản hồi JSON từ web.Để sử dụng thư viện này trong phản hồi Python và Fetch JSON, chúng tôi phải nhập JSON và Urllib trong mã của chúng tôi, JSON.Phương thức tải () Trả về đối tượng JSON.there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json. loads() method returns JSON object.