How to load data from JSON to Highchart?

后端 未结 4 2259
-上瘾入骨i
-上瘾入骨i 2021-01-15 07:09

my Json looks like this:

[{\"1332879360000.0\": 300.0, \"1332797760000.0\": 353.0,

\"1332799320000.0\": 358.0, \"1332         


        
4条回答
  •  失恋的感觉
    2021-01-15 07:20

    Here is a minimal working example of a solution. You can parse your data object using Object.keys and Array.prototype.map, at the end you want to sort your array of data with Array.prototype.sort.

    const json = [{
      "1332879360000.0": 300.0,
      "1332797760000.0": 353.0,
      "1332799320000.0": 358.0,
      "1332879780000.0": 302.0,
      "1332800160000.0": 359.0,
      "1332880200000.0": 299.0,
      "1332880620000.0": 298.0,
      "1332881040000.0": 301.0,
      "1332881460000.0": 402.0,
      "1332880020000.0": 330.0,
      "1332882300000.0": 466.0,
      "1332796620000.0": 519.0,
      "1332800520000.0": 447.0,
      "1332797460000.0": 359.0,
      "1332801000000.0": 442.0
    }]
    
    const options = {
      xAxis: { type: 'datetime' },
      series: [{
        // Get array of keys from your json object
        data: Object.keys(json[0])
          // Map your keys to arrays with x and y values
          .map((key) => [Number(key), json[0][key]])
          // Sort your data
          .sort((a, b) => a[0] - b[0]),
      }]
    }
    
    const chart = Highcharts.chart('container', options);
    

    Live example: https://jsfiddle.net/33hd8jog/

    [EDIT]

    I also created an example using data fetching from server:

    const url = 'https://rawgit.com/stpoa/7d44ff0db61515dae80ad021b7c6c01a/raw/800735764d6596512a5fbc69acad019ed0416d8f/data.json'
    
    window.fetch(url).then(response => response.json()).then(json => {
      const options = {
        xAxis: { type: 'datetime' },
        series: [{
          // Get array of keys from your json object
          data: Object.keys(json[0])
            // Map your keys to arrays with x and y values
            .map((key) => [Number(key), json[0][key]])
            // Sort your data
            .sort((a, b) => a[0] - b[0]),
        }]
      }
    
      const chart = Highcharts.chart('container', options)
    })
    

    Live example: https://jsfiddle.net/gxb6j2tz/

提交回复
热议问题