I
I
ivan_ivanov_ivanych2021-02-04 17:14:09
JavaScript
ivan_ivanov_ivanych, 2021-02-04 17:14:09

Why can't I process the JSON file correctly?

Good afternoon, dear forum users!

Given a JSON file:

{
  "exams":{
    "1":{
      "title":"ЕГЭ",
      "subjects":{
        "1":{
          "title":"Математика",
          "nums":{
            "1":{
              "themes":[
                {
                  "title":"Вычисления",
                  "id":1,
                  "questions_count":10
                },
                {
                  "title":"Округления",
                  "id":2,
                  "questions_count":15
                },
                {
                  "title":"Проценты",
                  "id":2,
                  "questions_count":12
                }
              ]
            },
            "all_questions_count":37
          }
        }
      }
    }
  }
}
```

The problem is that I can’t work it out and use it in a React application (I tried to convert it to an array, I used for..in, it always gives incorrect data. I get JSON via API, there is no way to change it.
My code:
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class App extends React.Component{
  constructor(props) {
    super(props)

    this.state = {
      data: [],
      isLoaded: false
    }


   //Тут получаю его по URL 
    window.onload = () => {
      window.fetch(urlForGetAllInfo)
      .then(responce => responce.json())
      .then((data) => {
        this.setState({
// И отправляю в состояние 
          data,
          isLoaded: true
        })
      })
      .catch((error) => {
        console.error(error.name + ' ОШИБКА ' + error.massage)
      })
    }
}
//Пытаюсь вернуть каждый контент, но title - undefined
getExamsContents = (exams) => {
  let content = [];
  for (let exam in exams) {
    content.push(<p key={exam}>{exam.title}</p>)
    console.log(content)
  }
  console.log(content)

  return content;
}
 

  render() {
    const {data, isLoaded} = this.state
    if (!isLoaded) {
      return (
        <div>Loading...</div>
      )
    }
    if (data.length !== 0) {
      return (
        <div>
            {this.getExamsContents(data.exams)}
          
        </div>
      )
    } 

  }

}

export default App;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kovalsky, 2021-02-04
@ivan_ivanov_ivanych

for (let exam in exams) {
    content.push(<p key={exam}>{exam.title}</p>)
    console.log(content)
  }

Exam is the key here, and you need to search for the object you need by referring to exams using this key: exams[exam]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question