@developer0101

Как получить доступ к свойству объекта JSON не зная его название?

В качестве сайта для парсинга выбрал Википедию.
Вот код:
import requests
import json

response = requests.get(url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Apple")
info = json.loads(response.text)

В info записывается следующая информация:
{"batchcomplete":"",
"query":{
    "pages":{
        "18978754":{
            "pageid":18978754,
            "ns":0,
             "title":"Apple",
             "extract":"An apple is a round, edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found. Apples have been grown for thousands of years in Asia and Europe and were introduced to North America by European colonists. Apples have religious and mythological significance in many cultures, including Norse, Greek, and European Christian tradition.\nApples grown from seed tend to be very different from those of their parents, and the resultant fruit frequently lacks desired characteristics. Generally, apple cultivars are propagated by clonal grafting onto rootstocks. Apple trees grown without rootstocks tend to be larger and much slower to fruit after planting. Rootstocks are used to control the speed of growth and the size of the resulting tree, allowing for easier harvesting.\nThere are more than 7,500 cultivars of apples. Different cultivars are bred for various tastes and uses, including cooking, eating raw, and cider production. Trees and fruit are prone to fungal, bacterial, and pest problems, which can be controlled by a number of organic and non-organic means. In 2010, the fruit's genome was sequenced as part of research on disease control and selective breeding in apple production.\nWorldwide production of apples in 2021 was 93 million tonnes, with China accounting for nearly half of the total."
            }
        }
    }
}

Мне нужно вывести информацию из "extract". Но объект "18978754" для каждой статьи представляет разное число (т.е. способом print(info["query"]["pages"]["18978754"]["extract"]) не получится). Вопрос такой: Как получить доступ к свойству объекта "extract" не зная его название?
  • Вопрос задан
  • 195 просмотров
Решения вопроса 3
Vindicar
@Vindicar
RTFM!
JSON-объекты загружаются в простой питоновский словарь (а массивы - в список).
Так что окей, гугл, перебор элементов словаря python.

В твоём случае что-то вроде
pages = info["query"]["pages"]
for page_id, page_data in pages.items():
    ...   # что-то делаешь с page_id и page_data


Если ты уверен, что у тебя всегда ровно один элемент в словаре, и его ключ тебя не интересует, то можно и так:
pages = info["query"]["pages"]
if pages:  # есть что-то в словаре?
    page_data = list(pages.values())[0]
    ...   # работаешь с page_data
Ответ написан
Mike_Ro
@Mike_Ro Куратор тега Python
Python, JS, WordPress, SEO, Bots, Adversting
Как получить доступ к свойству объекта "extract" не зная его название?

Итерированием объекта (если имеются вложенные объекты, то нужно обходить рекурсивно).

Предположим, у нас имеется json объект, далее мы его итерируем и печатаем ключи и их значения (не зная названия ключей заранее):
data = {
    "batchcomplete": "",
    "query": {
        "pages": {
            "18978754": {
                "pageid": 18978754,
                "ns": 0,
                "title": "Apple",
                "extract": "An apple is a round, edible fruit..."
            }
        }
    }
}

def print_key_value_pairs(obj, indent=0):
    if isinstance(obj, dict):
        for key, value in obj.items():
            print(' ' * indent + f"Key: {key}")
            if isinstance(value, (dict, list)):
                print_key_value_pairs(value, indent+4)
            else:
                print(' ' * (indent+4) + f"Value: {value}")
    elif isinstance(obj, list):
        for index, item in enumerate(obj):
            print(' ' * indent + f"Index: {index}")
            print_key_value_pairs(item, indent+4)

print_key_value_pairs(data)
Ответ написан
Maksim_64
@Maksim_64
Data Analyst
Можно использовать pandas. Нормализовать json, кода всего ничего будет.
import requests
import json
import pandas as pd
response = requests.get(url="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Apple")
info = json.loads(response.text)
df = pd.json_normalize(info)
print(df.iloc[:,-1][0])


Более правильный способ будет брать колонку не iloc а regex выраженим в pandas так можно, потому что, название колонки будет содержать весь путь до extract и заканчиваться на exctract. То есть возможна более сложная и стабильная выборка. То есть вот так
print(df.filter(regex='extract$',axis=1).iloc[0,0])
Результат идентичный, но так на много надежнее, мы не надеемся что нужная нам колонка последняя, а находим ее независимо от ее положения.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы