38
Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.
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
Đã trả lời ngày 8 tháng 10 năm 2012 lúc 19:35Oct 8, 2012 at 19:35
dm03514dm03514dm03514
53.4K18 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.
Đã trả lời ngày 17 tháng 8 năm 2015 lúc 20:49Aug 17, 2015 at 20:49
ButtersbbuttersbButtersB
4651 Huy hiệu vàng7 Huy hiệu bạc13 Huy hiệu đồng1 gold badge7 silver badges13 bronze badges
0
Dưới đây là một ví dụ về việc tải một giá trị duy nhất từ dữ liệu JSON đơn giản và chuyển đổi qua lại thành JSON:
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']]
Đã trả lời ngày 19 tháng 2 năm 2016 lúc 16:27Feb 19, 2016 at 16:27
1
Thử cái này.
Ở đây, tôi chỉ tìm nạp mã tượng từ API Covid [một mảng JSON].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']]
Đã trả lời ngày 14 tháng 4 năm 2021 lúc 12:43Apr 14, 2021 at 12:43
2
Thử cái này:
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 >> 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
4.6616 Huy hiệu vàng54 Huy hiệu bạc86 Huy hiệu Đồng6 gold badges54 silver badges86 bronze badges
Đã trả lời ngày 11 tháng 6 năm 2021 lúc 15:29Jun 11, 2021 at 15:29
1