Как проанализировать JSON вложенный в список из bls.gov для использования в реагировать-диаграмму js -2 - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь использовать API, предоставленный bls.gov - в частности https://api.bls.gov/publicAPI/v1/timeseries/data/CES0000000001 и разбить его на отдельные переменные (?) Для использования в реагировать -chart js -2 .

Мне удалось выяснить, как его получить, и добавить необработанный вывод JSON на мой сайт. Сейчас я пытаюсь правильно проанализировать JSON, чтобы его можно было добавить в диаграмму. js.

Вот код, который я использовал для получения из API. В настоящее время он выдает всплывающее предупреждение на сайте с необработанным JSON из запроса GET.

import React, { Component } from 'react'

class Testing extends Component {
    getDataUsingGet() {
        // Get request
        fetch('https://api.bls.gov/publicAPI/v1/timeseries/data/CES0000000001',{
            method: 'GET'
            // Request type
        })
        .then((response) => response.json())
        // If response is in json then in success
            .then((responseJson) => {
                //Success
                alert(JSON.stringify(responseJson));
                const obj = JSON.parse(responseJson);
                // ... Code for parsing to go here?

                console.log(responseJson)
            })
        // If response is not in json then throw error
            .catch((error) => {
                //Error
                alert(JSON.stringify(error))
                console.error(error)
            });
    }

    render() {
        return(
            <div>
                {/* Render the alert message in browser */}
                { this.getDataUsingGet() }
            </div>
        );
    }
}

export default Testing

Это формат JSON из запроса GET.

{
    "status": "REQUEST_SUCCEEDED",
    "responseTime": 177,
    "message": [],
    "Results": {
        "series": [
            {
                "seriesID": "CES0000000001",
                "data": [
                    {
                        "year": "2020",
                        "period": "M03",
                        "periodName": "March",
                        "latest": "true",
                        "value": "151786",
                        "footnotes": [
                            {
                                "code": "P",
                                "text": "preliminary"
                            }
                        ]
                    },
                    {
                        "year": "2020",
                        "period": "M02",
                        "periodName": "February",
                        "value": "152487",
                        "footnotes": [
                            {
                                "code": "P",
                                "text": "preliminary"
                            }
                        ]
                    },
...

И, наконец, это код, который я использую для создания диаграммы с react-chartjs-2. В настоящее время он заполнен образцами данных из примера диаграммы.

import React, { Component } from 'react';
import {Bar} from 'react-chartjs-2';

// TESTING FOR FETCHING API FROM WWW.BLS.GOV
// Data input for the RateChart chart.js generation -> 'data'
const data = {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [
        {
            label: 'US Unemployment Rate',
            backgroundColor: 'rgba(255,99,132,0.2)',
            borderColor: 'rgba(255,99,132,1)',
            borderWidth: 1,
            hoverBackgroundColor: 'rgba(255,99,132,0.4)',
            hoverBorderColor: 'rgba(255,99,132,1)',
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

const RateChart = () => {
    return (
        <div>
            <h2>Current unemployment</h2>
            <Bar
                data={data}
                width={100}
                height={50}
                options={{
                    responsive: true,
                    maintainAspectRatio: true
                }}
            />
        </div>
    );
}

export default RateChart;


В итоге: Как мне взять JSON, разбить его на year, periodName, и value, чтобы их можно было добавить в мой RateChart компонент, используя jsx / javascript?

Спасибо

Ответы [ 3 ]

1 голос
/ 19 апреля 2020

Попробуйте что-то вроде этого, чтобы разобрать это json. Вам нужно будет добавить нулевые уловления и тому подобное, когда вы не получите успешный ответ, но в зависимости от того, какой код вы предоставили, это должно работать.

Кроме того, с точки зрения синтаксиса, вы, вероятно, должны только возвращать ответ. json и сделать функцию getDataUsingGet асинхронной, дождаться вызова выборки, а затем обработать ответ! Это намного чище рабочий процесс, чем вложение .thens

 class Testing extends Component {
        getDataUsingGet() {
            // Get request
            fetch('https://api.bls.gov/publicAPI/v1/timeseries/data/CES0000000001',{
                method: 'GET'
                // Request type
            })
            .then((response) => response.json())
            // If response is in json then in success
                .then((responseJson) => {
                    //Success
                    alert(JSON.stringify(responseJson));
                    const obj = responseJson;
                    // ... Code for parsing to go here?
                    for(var i = 0; i < obj.Results.series.length; i++){
                        series = obj.Results.series[i];
                        for(var j = 0; j < series.data.length; j++){
                            console.log(series.data[j].year)
                            console.log(series.data[j].period)
                        }
                    }


                })
            // If response is not in json then throw error
                .catch((error) => {
                    //Error
                    alert(JSON.stringify(error))
                    console.error(error)
                });
        }

        render() {
            return(
                <div>
                    {/* Render the alert message in browser */}
                    { this.getDataUsingGet() }
                </div>
            );
        }
    }

    export default Testing
0 голосов
/ 19 апреля 2020

const obj = {}

axios.get('https://api.bls.gov/publicAPI/v1/timeseries/data/CES0000000001')
      .then(function(response){
      const res = response.data.Results.series[0].data

      res.map(data=>{
        obj.period = data.period // same for the rest
      })
      });  
0 голосов
/ 19 апреля 2020

Вы можете сделать что-то вроде:

let result = json.Results.series.map((serie) =>
  serie.data.map(({ year, periodName, value }) => ({
    year,
    periodName,
    value,
  }))
);

let json = {
  status: "REQUEST_SUCCEEDED",
  responseTime: 214,
  message: [],
  Results: {
    series: [{
      seriesID: "CES0000000001",
      data: [{
          year: "2020",
          period: "M03",
          periodName: "March",
          latest: "true",
          value: "151786",
          footnotes: [{
            code: "P",
            text: "preliminary",
          }, ],
        },
        {
          year: "2020",
          period: "M02",
          periodName: "February",
          value: "152487",
          footnotes: [{
            code: "P",
            text: "preliminary",
          }, ],
        },
        {
          year: "2020",
          period: "M01",
          periodName: "January",
          value: "152212",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M12",
          periodName: "December",
          value: "151998",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M11",
          periodName: "November",
          value: "151814",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M10",
          periodName: "October",
          value: "151553",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M09",
          periodName: "September",
          value: "151368",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M08",
          periodName: "August",
          value: "151160",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M07",
          periodName: "July",
          value: "150953",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M06",
          periodName: "June",
          value: "150759",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M05",
          periodName: "May",
          value: "150577",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M04",
          periodName: "April",
          value: "150492",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M03",
          periodName: "March",
          value: "150282",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M02",
          periodName: "February",
          value: "150135",
          footnotes: [{}],
        },
        {
          year: "2019",
          period: "M01",
          periodName: "January",
          value: "150134",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M12",
          periodName: "December",
          value: "149865",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M11",
          periodName: "November",
          value: "149683",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M10",
          periodName: "October",
          value: "149549",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M09",
          periodName: "September",
          value: "149348",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M08",
          periodName: "August",
          value: "149268",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M07",
          periodName: "July",
          value: "149024",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M06",
          periodName: "June",
          value: "148888",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M05",
          periodName: "May",
          value: "148669",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M04",
          periodName: "April",
          value: "148391",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M03",
          periodName: "March",
          value: "148254",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M02",
          periodName: "February",
          value: "148078",
          footnotes: [{}],
        },
        {
          year: "2018",
          period: "M01",
          periodName: "January",
          value: "147672",
          footnotes: [{}],
        },
      ],
    }, ],
  },
};

let result = json.Results.series.map((serie) =>
  serie.data.map(({
    year,
    periodName,
    value
  }) => ({
    year,
    periodName,
    value,
  }))
);

console.log(result);
...