以下是我的资源:
我的pageviews.json文件内容:
[
{"day":1,"pageviews":"687928"},
{"day":2,"pageviews":"688331"},
{"day":3,"pageviews":"603741"},
{"day":4,"pageviews":"542002"},
{"day":5,"pageviews":"657730"},
{"day":6,"pageviews":"804183"},
{"day":7,"pageviews":"776029"},
{"day":8,"pageviews":"654589"}
]
我正在尝试使用以下内容呈现morris.js折线图:
$(document).ready(function() {
$.getJSON("pageviews.json", function (json) {
var jason_data = JSON.stringify(json);
var jasonstuff = (jason_data.replace(/\"/g, ""));
Morris.Line({
element: 'mydiv',
data: jason_data,
xkey: 'day',
ykeys: ['pageviews'],
labels: ['PageViews']
});
});
});
var jasonstuff输出JSON没有引号。
[{day:1,pageviews:687928},{day:2,pageviews:688331},{day:3,pageviews:603741},{day:4,pageviews:542002},{day:5,pageviews:657730},{day:6,pageviews:804183},{day:7,pageviews:776029},{day:8,pageviews:654589}]
我得到的错误:
未捕获的TypeError:无法读取属性'匹配'未定义的
这似乎在xkey
和ykeys
值处分崩离析。我知道我必须会遗漏一些非常愚蠢的东西。有人有建议吗?
答案 0 :(得分:1)
您不应该对从.getJSON()
返回的数据进行字符串化。你也不应该试图取代报价。您已经误解了JSON字符串和本机Javascript对象之间的区别。
Morris期待一个Javascript对象(或一个对象数组)。你的pageviews.json
在技术上是一个大字符串。 .getJSON()
所做的是获取该文件并将其从字符串转换为本机对象。
var myString = '{"day":1,"pageviews":"687928"}';
var myObject = {day: 1, pageviews: "687928"};
通过对从.getJSON()
返回的数据进行字符串化,您实际上将本机对象重新转换回字符串,而莫里斯并不理解。引号也不是问题,除了它们必须在字符串中,以便它被视为有效的JSON格式。只需将.getJSON()
返回的JSON对象直接提供给Morris。
$.getJSON("pageviews.json", function (json) {
Morris.Line({
element: 'mydiv',
data: json,
xkey: 'day',
ykeys: ['pageviews'],
labels: ['PageViews']
});
});
注意:您的pageviews: "687928"
属性会将数字存储为pageviews.json
文件中的字符串。您可能希望在将其读入应用程序之前将其转换为文件,否则您需要解析该值(除非Morris为您执行此操作)。
答案 1 :(得分:0)
此处数据是一个对象数组,包含xkey
和ykeys
选项所描述的x和y属性。请检查此Plunker
var data=[
{"day":"1","pageviews":"687928"},
{"day":"2","pageviews":"688331"},
{"day":"3","pageviews":"603741"},
{"day":"4","pageviews":"542002"},
{"day":"5","pageviews":"657730"},
{"day":"6","pageviews":"804183"},
{"day":"7","pageviews":"776029"},
{"day":"8","pageviews":"654589"}
]
Morris.Line({
element: 'mydiv',
data: data,
xkey: ['day'],
ykeys: ['pageviews'],
labels: ['PageViews'],
parseTime : false
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="https://cdn.jsdelivr.net/morris.js/0.4.1/morris.min.js"></script>
<div id="mydiv"></div>
&#13;
答案 2 :(得分:0)
根据你的json我生成图表 请在下面找到链接并查看
我尝试下面的代码,它的工作正常
var jason_data = [{day:1,pageviews:687928},{day:2,pageviews:688331},{day:3,pageviews:603741},{day:4,pageviews:542002},{day:5,pageviews:657730},{day:6,pageviews:804183},{day:7,pageviews:776029},{day:8,pageviews:654589}];
Morris.Line({
element: 'line-example',
data: jason_data,
xkey: 'day',
ykeys: ['pageviews'],
labels: ['PageViews']
});