繁体   English   中英

如何使用d3访问JSON数据?

[英]How to access JSON data using d3?

我有一个JSON数据类型,该数据类型存储在模型中以传递给视图。 我也有一个条形图,我想用它来显示数据。 但是,我只想显示一些字段,即SupplierName和Query。 我已经按照d3教程进行操作,以获取图形,但这是我第一次将其付诸实践。

有人知道如何执行此操作吗?

控制器:

   public ActionResult ValueBySupplierAndClaimType(int ClientID, int ReviewPeriodID, int StatusCategoryID) {
            ValueBySupplierAndClaimTypeViewModel model = new ValueBySupplierAndClaimTypeViewModel {
                ReportData = reportRepo.GetValueBySupplierAndClaimType(ClientID, ReviewPeriodID, StatusCategoryID),
                ReportTitle = "Dashboard Breakdown",
                ReportDescription = "Breakdown for " + reviewRepo.GetAllReviewsByClientID(ClientID).Where(r => r.ReviewID == ReviewPeriodID).Select(r => r.ReviewPeriod).FirstOrDefault()
            };

            model.output = JsonConvert.SerializeObject(model.ReportData, Formatting.Indented);

            return View("ValueBySupplierAndClaimType", model);

JSON:

[  
  {
    "SupplierID": 4336,
    "SupplierName": "Test1",
    "AccountNo": 09579
    "Claim": null,
    "Normal": null,
    "Query": 1000.0000,
    "Formal": null,
    "Strong": null,
    "Unsubstantiated": null
  },
  {
    "SupplierID": 4357,
    "SupplierName": "Test2                 ",
    "AccountNo": 00124
    "Claim": null,
    "Normal": null,
    "Query": 9000.0000,
    "Formal": null,
    "Strong": null,
    "Unsubstantiated": null
  },
  {
    "SupplierID": 4395,
    "SupplierName": "Test3                   ",
    "AccountNo": 00001
    "Claim": null,
    "Normal": null,
    "Query": null,
    "Formal": null,
    "Strong": null,
    "Unsubstantiated": null
  }
]

D3:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>

    var margin = { top: 20, right: 20, bottom: 30, left: 40 },
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .1);

    var y = d3.scale.linear()
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(10, "%");

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.csv(@Model.output, type, function (error, data) {
        if (error) throw error;

        data.forEach(function(d) {

            //(function(d) {return d.SupplierName})
            //(function(d) {return d.Query})

            x.domain(data.map(function (d) { return d.SupplierName }));
            y.domain([0, d3.max(data, function (d) { return d.Query })]);

        })


        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
          .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text("Query");

        svg.selectAll(".bar")
            .data(data)
          .enter().append("rect")
            .attr("class", "bar")
            .attr("x", function (d) { return x(d.SupplierName); })
            .attr("width", x.rangeBand())
            .attr("y", function (d) { return y(d.Query); })
            .attr("height", function (d) { return height - y(d.Query); });
    });

    function type(d) {
        d.Query = +d.Query;
        return d;
    }


</script>

我尝试查看一些答案,但是尝试实现它们,但是似乎没有任何效果

您的代码有两个问题:

JSON格式

JsonConvert.SerializeObject()返回JSON(如名称所示)而不是CSV。 因此,您应该使用d3.json ,但是

请求

d3.csvd3.jsonURL作为第一个参数,并触发XMLHttpRequest以获取数据,在加载时解析数据并将其传递给回调。

您的@Model.output包含带有完整JSON的字符串。 您不需要请求数据,因为您已经将其作为字符串。 您只需要像这样使用JSON.parse()解析字符串:

...
//d3.csv(@Model.output, type, function (error, data) {
try {
  var data = JSON.parse("@Model.output");

  data.forEach(function(d){
    x.domain(data.map(function (d) { return d.SupplierName }));
    y.domain([0, d3.max(data, function (d) { return d.Query })]);
  });
  ...
} catch(e){
  ...
}

确保使用try-catch,因为JSON.parse可能因无效的JSON而失败。

暂无
暂无

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

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