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': '//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": "//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": "//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": "//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ỏ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": "//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": "//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": "//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": "//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": "//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": "//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": "//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": "//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
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['//api.covid19india.org/data.json']
x = r.json[]['statewise']
for i in x:
print[i['statecode']]
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": "//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
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 >> 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": "//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": "//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'
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
1