Hướng dẫn get value of json object python - lấy giá trị của đối tượng json python

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': '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 get value of json object python - lấy giá trị của đối tượng json python

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

Đã 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": "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.

Đã 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

Hướng dẫn get value of json object python - lấy giá trị của đối tượng json python

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('https://api.covid19india.org/data.json')

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

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

Hướng dẫn get value of json object python - lấy giá trị của đối tượng json python

Đã trả lời ngày 14 tháng 4 năm 2021 lúc 12:43Apr 14, 2021 at 12:43

Hướng dẫn get value of json object python - lấy giá trị của đối tượng json python

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 <= sub < length else None
        else:
            return None
    return out_data


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

Sau đó, bạn có thể sử dụng nó như dưới đây:

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 get value of json object python - lấy giá trị của đối tượng json python

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

Hướng dẫn get value of json object python - lấy giá trị của đối tượng json python

1

Làm cách nào để trích xuất một giá trị từ tệp JSON trong Python?

Vì vậy, điều đầu tiên bạn cần nhập mô -đun 'JSON' vào tệp. Sau đó tạo một chuỗi đối tượng JSON đơn giản trong Python và gán nó cho một biến. Bây giờ chúng tôi sẽ sử dụng hàm tải () từ mô -đun 'JSON' để tải dữ liệu JSON từ biến. Chúng tôi lưu trữ dữ liệu JSON dưới dạng chuỗi trong Python với ký hiệu trích dẫn.

Làm thế nào để bạn truy cập dữ liệu từ một đối tượng JSON trong Python?

Đọc từ JSON, thật dễ dàng để tải một đối tượng JSON trong Python. Python có một gói tích hợp có tên JSON, có thể được sử dụng để làm việc với dữ liệu JSON. Nó được thực hiện bằng cách sử dụng mô -đun JSON, cung cấp cho chúng tôi rất nhiều phương thức trong số các phương thức tải () và tải () sẽ giúp chúng tôi đọc tệp JSON.using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

Làm cách nào để trích xuất giá trị từ JSON?

Để trích xuất các thuộc tính tên và dự án từ chuỗi JSON, hãy sử dụng chức năng JSON_EXTRACT như trong ví dụ sau.Hàm JSON_EXTRACT lấy cột chứa chuỗi JSON và tìm kiếm nó bằng biểu thức giống JsonPath với dấu chấm.ký hiệu.JsonPath thực hiện một đường truyền cây đơn giản.use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.

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.