@Xonezz
Обучаюсь веб разработке

Как распарсить возвращаемые данные JSON?

Есть следующий код:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Find IP</title>
  </head>
  <body>
    <div class="main-page">
      <div class="content-conatainer">
        <h1>Определить местоположение</h1>
        <div class="data-input">
          <input type="text" id= "find" class="input-text" name="ip" value="" />
          <input type="submit" class="input-button" value="Проверить" />
        </div>
      </div>
    </div>
    <script src="/index.js"></script>
  </body>
</html>

var url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/iplocate/address?ip=";
var token = "xxx";
const query = document.getElementById('find').value;
console.log(query);

var options = {
    method: "GET",
    mode: "cors",
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Token " + token
    }
}

fetch(url + query, options)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));

Как сделасть так чтобы из получаемого ответа выводить в HTML:
Страна:
Регион:
Город:
  • Вопрос задан
  • 296 просмотров
Решения вопроса 2
alexey-m-ukolov
@alexey-m-ukolov Куратор тега JavaScript
Для начала нужно заменить .then(response => response.text()) на .then(response => response.json()). И потом работать с result как с обычным объектом.
Ответ написан
Комментировать
sergiks
@sergiks Куратор тега JavaScript
♬♬
см. формат ответа в документации
-.then(response => response.text())
-.then(result => console.log(result))
+.then(response => response.json())
+.then(({ location }) => {
+  if (!location) return; // не нашлось
+  const { data } = location;
+  const { country, region_with_type, city_with_type } = data;
+  // теперь их куда-то вставить в разметку
+})
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
29 мар. 2024, в 11:11
10000 руб./за проект
29 мар. 2024, в 10:00
10000 руб./за проект
29 мар. 2024, в 09:59
750 руб./в час