javascript - 如何解析嵌套在 bls.gov 列表中的 JSON 以在 React-chartjs-2 中使用

标签 javascript json reactjs api parsing

我正在尝试使用bls.gov提供的API - 具体来说https://api.bls.gov/publicAPI/v1/timeseries/data/CES0000000001并将其分解为单独的变量(?)以在 react-chartjs-2 中使用.

我已经设法弄清楚如何获取它,并将原始 JSON 输出添加到我的网站。我现在想做的是正确解析 JSON,以便可以将其添加到 Chart.js 中。

这是我用来从 API 获取的代码。目前,它会在网站上发出弹出警报,其中包含来自 GET 请求的原始 JSON。

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

这是 GET 请求中的 JSON 格式。

{
    "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,将其分解为 yearperiodNamevalue 以便将它们添加到我的 RateChart 中 组件使用 jsx/javascript?

谢谢

最佳答案

尝试这样的方法来解析该 json。当您没有获得成功的响应时,您将需要添加空捕获等,但根据您提供的代码,这应该可以工作。

此外,在语法方面,您可能应该只返回response.json,并使 getDataUsingGet 函数异步,等待 fetch 调用,然后处理响应!这是一个比嵌套更干净的工作流程。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

关于javascript - 如何解析嵌套在 bls.gov 列表中的 JSON 以在 React-chartjs-2 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61300430/

相关文章:

javascript - 试图找出如何重新格式化 JSON 响应并重新格式化数据

javascript - React Alt Babel IE9-10 失败但没有错误

reactjs - 如何在 Webpack 配置文件中将 CSS 名称设置为不是哈希值?

javascript - 以编程方式在 Dynamics CRM 2011 中注册 OnLoad 处理程序(用于表单)

python - Python 或 Django 中的 CURL

javascript - 连接没有索引 0 的 JSON 数组对象未定义

javascript - 在react中将onChange传递给子组件

javascript - 鼠标悬停使 div 出现在图像的边框内

javascript - 用链接和 chop 值替换 anchor

javascript - jQuery 正则表达式返回意外结果