代码之家  ›  专栏  ›  技术社区  ›  stone rock

如何从json中提取数据并将其注入到图表中?

  •  0
  • stone rock  · 技术社区  · 7 年前

    我正在制作一个条形图组件,并将其导入到 app.js . 我的json数据包含板球比赛信息,即 season runs (即那个赛季的得分)。在y轴上,条形图的高度将是特定季节所有跑步记录的总和,在x轴上,标签将是季节。

    对于以下JSON示例:

    season 2008 -> runs = 100+200=300
    season 2009 -> runs = 300
    season 2010 -> runs = 1100
    season 2011 -> runs = 100
    

    JSON数据:

    [
        { 
          "season":2008,
          "runs":100
        },
        { 
          "season":2008,
          "runs":200
        },
        { 
          "season":2009,
          "runs":300
        },
        { 
          "season":2010,
          "runs":600
        },
        { 
          "season":2010,
          "runs":500
        },
        { 
          "season":2011,
          "runs":100
        }   
    ]
    

    图表组件:

    import React, { Component } from 'react';
    import ChartistGraph from 'react-chartist';
    
    const ChartData = {
    
      //labels are the season
    
      labels: [ ],
    
      series: [
        // runs will be injected here
      ],
       distributeSeries: true
    }
    
    const options = {
        width: 720,
        height: 400
    }
    
    class Chart extends Component {
    
      render(){
        return(
          <div>
             <ChartistGraph data={ChartData} type={'Bar'} options={options}/>
          </div>
        )}
    
    }
    
    export default Chart;
    

    如何从json数据中插入数据而不是硬编码 季节 作为 labels 作为 series . 我尝试使用for循环,但无法获取特定的运行总数 季节 . 为:为了 season 2008 它应该是100+200=300,即label=2008,与之对应的系列元素将是 300 .

    注意:对于给定的json数据系列将是:

    series:[300, 300, 1100, 100]

    3 回复  |  直到 7 年前
        1
  •  2
  •   Jaromanda X    7 年前

    使用array reduce合并季节,使用另一个reduce创建两个数组

    var json = `[
        { 
          "season":2008,
          "runs":100
        },
        { 
          "season":2008,
          "runs":200
        },
        { 
          "season":2009,
          "runs":300
        },
        { 
          "season":2010,
          "runs":600
        },
        { 
          "season":2010,
          "runs":500
        },
        { 
          "season":2011,
          "runs":100
        }   
    ]`
    
    var data = Object.entries(JSON.parse(json).reduce((acc, {season, runs}) => (acc[season] = (acc[season] || 0) + runs, acc), {}))
        .reduce((acc, [labels, series]) => (acc.labels.push(labels), acc.series.push(series), acc),{labels: [], series:[]}) 
        console.log(data)

    在ES5中逐步分解

    var json = `[
        { 
          "season":2008,
          "runs":100
        },
        { 
          "season":2008,
          "runs":200
        },
        { 
          "season":2009,
          "runs":300
        },
        { 
          "season":2010,
          "runs":600
        },
        { 
          "season":2010,
          "runs":500
        },
        { 
          "season":2011,
          "runs":100
        }   
    ]`
    var data = JSON.parse(json); // because JSON is a string representation of an javascript object
    var data1 = data.reduce(function (acc, item) {
        var season = item.season,
            runs = item.runs;
        acc[season] = acc[season] || 0; // add a season as a key
        acc[season] += runs; // add runs
        return acc;
    }, {});
    console.log(data1); 
    var data2 = Object.entries(data1); // make an array of [[label, runs],[label, runs]...]
    console.log(data2); 
    var data3 = data2.reduce(function (acc, item) { // each item is an array of [year, total runs]
        var labels = item[0],
            series = item[1];
    
        acc.labels.push(labels);
        acc.series.push(series); 
        return acc;
    }, { labels: [], series: [] }); // initialise the return object
    console.log(data3);
        2
  •  1
  •   someRandomSerbianGuy    7 年前

    创建新数组,遍历当前数组的所有元素,按其键对其进行分析,并查看新数组中的值是否唯一(如果未添加到该值,则为create new element)。

    function fillGraph(data){
    var newArray = []; //creating new, empty array
        for(var i = 0; i < data.length; i++){ //going through all elements of data array
            if(newArray.hasOwnProperty(data[i]["season"]){ //if it already has that season
                newArray["season"] += data[i]["runs"]; //add runs to the current season
            }else{
                newArray.push({data[i]["season"] : data[i]["runs"]}); //if not create new object with key name as a season name and assign runs
            }
        }
        for(var i in newArray) { //go through our new array
            chartData.labels.push(i); //push key name of current array element into graph labels property
            chartData.series.push(newArray[i]); //push value of current array element into graph series property
        });
    }
    
        3
  •  0
  •   SNovak    6 年前

    分享我对任务的看法

     <script>
                // in the url variable I use a link to my JSON, so might try you by 
                // firstly uploading your JSON at myjson.com
                let url = 'https://api.myjson.com/bins/8x9l7'; 
    
                fetch(url).then(res => res.json()).then((out) => {
                    // here you might try console.log(out); to check the correctness of 
                    // displaying your JSON imported via URL
                    convertJsonToData(out);
                }).catch(err => { throw err });
    
                let data = {
                        labels: [],
                        series: [[]]
                    };
    
                function convertJsonToData(jsonData) { 
                    for (let x in jsonData) {
                        data.labels.push(jsonData[x].transactTime); //transactTime and walletBalance are keys in my JSON, you will have yours
                        data.series[0].push(jsonData[x].walletBalance);
                    };
                    // here you might try console.log(data); to check the correctness of 
                    // data display taken from JSON and modified to use in chart
                    return data;
                };
    
                 let options = {
                     showPoint: false,
                     lineSmooth: true,
                     fullWidth: true,
                     height: 700,
                     showArea:true,
                };
    
                 new Chartist.Line('.ct-chart', data, options);
    
              </script>