简体   繁体   English

如何将json数据动态链接到chart.js

[英]How to dynamically link json data to chart.js

I am trying to create a chart using json data.我正在尝试使用 json 数据创建图表。 Currently I have the data within my script, but I would like to link it to a separate .json file within the project folder.目前我的脚本中有数据,但我想将它链接到项目文件夹中的单独 .json 文件。

This is what I have currently:这是我目前所拥有的:

    var jsonfile = {
        "jsonarray": [{
            "name": "Joe",
            "age": 12
        }, {
            "name": "Tom",
            "age": 14
        }]
    };

    var labels = jsonfile.jsonarray.map(function(e) {
        return e.name;
    });

    var data = jsonfile.jsonarray.map(function(e) {
        return e.age;
    });

    var ctx = document.getElementById("chart");
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Graph Line',
                data: data,
                backgroundColor: 'rgba(0, 119, 204, 0.3)'
            }]
        }
    });

Ideally, I would like the json data to be in a separate file so that it can be dynamically saved.理想情况下,我希望 json 数据位于单独的文件中,以便可以动态保存。 Thanks :)谢谢 :)

You can use the fs module to read and write to a file您可以使用 fs 模块读取和写入文件

var fs = require('fs');
var jsonfile = fs.readFileSync('the/path');
//if you want to write to the file I gave you a link that shows you the way

For more information about the fs module you can check File System |有关 fs 模块的更多信息,您可以查看File System | Node.js v12.6.0 Documentation . Node.js v12.6.0 文档

You may need to pass by JSON.stringify and JSON.parse to save your object as a string in the file and to parse the string back to an object while reading the file.您可能需要通过JSON.stringifyJSON.parse将您的对象作为字符串保存在文件中,并在读取文件时将字符串解析回对象。

Another manner that you may consider is lightweight javascript databases such as IndexedDB which is an embedded database in the browser side, or other databases such as neDB if you want to persist data especially with an electron app.您可能会考虑的另一种方式是轻量级 javascript 数据库,例如IndexedDB ,它是浏览器端的嵌入式数据库,或者其他数据库,例如neDB,如果您想保留数据,尤其是使用电子应用程序。

Have many way to use with your wish有很多方法可以随心所欲地使用

var data = {"a" : "b", "c" : "d"};

then然后

<script src="data.js" ></script>

or或者

var json = require('./data.json');

or或者

$.getJSON("data.json", function(json) {
    console.log(json);
});

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM