Преобразование Promise в объект JSON с использованием fetch в JavaScript

Приведенный ниже код JavaScript пытается извлечь данные из API Википедии с помощью fetch; Тем не менее, он встречает следующую ошибку:

Код:

const endpoint = "https://en.wikipedia.org/w/api.php?action=opensearch&search=Hello&format=json&origin=*&callback=?";
fetch(endpoint).then(blob => console.log(blob.json()));

Ошибка:

index.html: 1 Uncaught (в обещании) SyntaxError: Неожиданный токен / в JSON в позиции 0

Вот что возвращает API:

/**/(["Hello",["Hello","Hello, Dolly! (musical)","Hello Kitty","Hello (Adele song)","Hello Venus","Helloween","Hello Counselor","Hello, Goodbye","Hello! Project","Hello, Dolly! (film)"],["Hello is a salutation or greeting in the English language. It is first attested in writing from 1826.","Hello, Dolly! is a 1964 musical with lyrics and music by Jerry Herman and a book by Michael Stewart, based on Thornton Wilder's 1938 farce The Merchant of Yonkers, which Wilder revised and retitled The Matchmaker in 1955. The musical follows the story of Dolly Levi (a strong-willed matchmaker), as she travels to Yonkers, New York, to find a match for the miserly \"well-known unmarried half-a-millionaire\" Horace Vandergelder.","Hello Kitty (Japanese: \u30cf\u30ed\u30fc\u30fb\u30ad\u30c6\u30a3, Hepburn: Har\u014d Kiti) (full name: Kitty White (\u30ad\u30c6\u30a3\u30fb\u30db\u30ef\u30a4\u30c8, Kiti Howaito)) is a fictional character produced by the Japanese company Sanrio, created by Yuko Shimizu and currently designed by Yuko Yamaguchi.","\"Hello\" is a song by English singer Adele, released on 23 October 2015 by XL Recordings as the lead single from her third studio album, 25 (2015).","Hello Venus (Hangul: \ud5ec\ub85c\ube44\ub108\uc2a4; often stylized as HELLOVENUS) is a South Korean girl group formed by Tricell Media, a joint venture between Pledis Entertainment and Fantagio, in 2012. The group originally consisted of six members: Alice, Nara, Lime, Yooara, Yoonjo, and Yooyoung.","Helloween is a German power metal band founded in 1984 in Hamburg, Northern Germany by members of bands Iron Fist and Gentry.","Hello Counselor (Hangul: \uc548\ub155\ud558\uc138\uc694; RR: Annyeonghaseyo; lit. Hello) is a South Korean reality show that debuted in November 2010. It is hosted by Shin Dong-yup, Lee Young-ja, and Cultwo (Jung Chan-woo, Kim Tae-gyun).","\"Hello, Goodbye\" is a song by the English rock band the Beatles, written by Paul McCartney and credited to Lennon\u2013McCartney.","Hello! Project (\u30cf\u30ed\u30fc!\u30d7\u30ed\u30b8\u30a7\u30af\u30c8, Har\u014d! Purojekuto) is a Japanese idol project, the umbrella name for a collective of female singers who are under contract with the Up-Front Group and whose recordings are produced by Tsunku.","Hello, Dolly! is a 1969 American romantic comedy musical film based on the Broadway production of the same name."],["https://en.wikipedia.org/wiki/Hello","https://en.wikipedia.org/wiki/Hello,_Dolly!_(musical)","https://en.wikipedia.org/wiki/Hello_Kitty","https://en.wikipedia.org/wiki/Hello_(Adele_song)","https://en.wikipedia.org/wiki/Hello_Venus","https://en.wikipedia.org/wiki/Helloween","https://en.wikipedia.org/wiki/Hello_Counselor","https://en.wikipedia.org/wiki/Hello,_Goodbye","https://en.wikipedia.org/wiki/Hello!_Project","https://en.wikipedia.org/wiki/Hello,_Dolly!_(film)"]])

Как вы можете заметить, ошибка является результатом того, что API возвращает строку, начинающуюся с /**/, которую метод.json() не может интерпретировать (согласно сообщению об ошибке).

Мой вопрос:

Учитывая, что я уже указал в своем вызове API вернуть мои данные в формате JSON (format=json), как мне следует учитывать тот факт, что.json() не может преобразовать возвращаемую строку в объект JSON?

Должен ли я просто вызвать метод.text() для blob, сохранить результат в строку, удалить символ / ** / и затем использовать JSON.parse() для преобразования строки в объект JSON?

Кроме того, есть ли причина, по которой Википедия добавляет / ** / перед возвращаемой строкой?

PS Я ищу решения в чистом JavaScript

0 ответов

Другие вопросы по тегам