Доступ к вложенным данным в ответе JSON Wiki API - PullRequest
0 голосов
/ 22 мая 2019

Я все еще относительно новичок во всем этом, но я пытаюсь получить доступ к API Википедии, чтобы извлечь значение «extract» и добавить текст в элемент html.Проблема в том, что «страницы» будут меняться в зависимости от ввода пользователя.Есть ли способ получить доступ к информации, заданной случайным числом в ответе JSON?* Редактировать - я использую Jquery / Javascript.это был запрос API, который я отправил: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Pug

{

"batchcomplete": "",
"query": {
    "normalized": [
        {
            "from": "pug",
            "to": "Pug"
        }
    ],
    "pages": {
        "21234727 (this number is will change/be random)": {
            "pageid": 21234727,
            "ns": 0,
            "title": "Pug",
            "extract": "The pug is a breed of dog with physically distinctive features of a wrinkly, short-muzzled face, and curled tail. The breed has a fine, glossy coat that comes in a variety of colours, most often fawn or black, and a compact square body with well-developed muscles.\nPugs were brought from China to Europe in the sixteenth century and were popularized in Western Europe by the House of Orange of the Netherlands, and the House of Stuart. In the United Kingdom, in the nineteenth century, Queen Victoria developed a passion for pugs which she passed on to other members of the Royal family.\nPugs are known for being sociable and gentle companion dogs. The American Kennel Club describes the breed's personality as \"even-tempered and charming\". Pugs remain popular into the twenty-first century, with some famous celebrity owners. A pug was judged Best in Show at the World Dog Show in 2004."
        }
    }
}

}

1 Ответ

0 голосов
/ 22 мая 2019

Извлечение - это хеш внутри случайным образом пронумерованного хеша, который находится внутри страниц хеша, который находится внутри запроса хэш Таким образом, вам нужно значение json->query->pages->random_number->extract.

Это требует присвоения имени случайному числу, чтобы вы знали, как обращаться к нему каждый раз. Вы не сказали, какой язык используете, но я бы попробовал что-то подобное в Perl (если вы предоставите свой язык по выбору, кто-то другой может показать соответствующую операцию):

foreach my $pagenum ( keys %{$json{'query'}{'pages'}}) {
  print "Random number is now called $pagenum\n"; 
my $extract = $json{'query'}{'pages'}{$pagenum}->{'extract'}; 
  print "Extract is $extract\n";
}

Результат печати $extract: The pug is a breed of dog with physically distinctive features of a wrinkly... и т. Д.

Я заставил моего сына перевести операцию Perl на Ruby, так что это тоже работает. (Предполагается, что JSON находится в переменной с именем json):

randnum = json['query']['pages'].keys[0]
extract_value = json['query']['pages'][randnum]['extract']
puts extract_value

ОБНОВЛЕНИЕ: (OP указанный язык)

Я не очень хорош с Javascript, но, похоже, это работает:

var extractValue = Object.values(your_json.query.pages)[0].extract; (где your_json - данные JSON, которые вы получили).

...