从 JSON 字符串而不是 JSON 文件渲染 D3 图 [英] Render D3 graph from a string of JSON instead of a JSON file

查看:23
本文介绍了从 JSON 字符串而不是 JSON 文件渲染 D3 图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 Rails 应用程序渲染以下树状图:http://bl.ocks.org/mbostock/4063570

I am trying to render the following Dendrogram from my Rails app: http://bl.ocks.org/mbostock/4063570

我有一个具有许多属性的模型,但我想手动嵌套这些属性并简单地使用字符串插值来构建我自己的 JSON 字符串,然后将其直接传递给 d3.

I have a model with many attributes, but I would like to manually nest those attributes and simply use string interpolation to build up my own JSON string, then pass that to d3 directly.

这是我的代码:

    <%= javascript_tag do %>
        var width = 960,
        height = 2200;

        var cluster = d3.layout.cluster()
        .size([height, width - 160]);

        var diagonal = d3.svg.diagonal()
        .projection(function(d) { return [d.y, d.x]; });

        var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(40,0)");

        **d3.json("/assets/flare.json", function(root) {**
        var nodes = cluster.nodes(root),
        links = cluster.links(nodes);

        var link = svg.selectAll(".link")
        .data(links)
        .enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal);

        var node = svg.selectAll(".node")
        .data(nodes)
        .enter().append("g")
        .attr("class", "node")
        .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

        node.append("circle")
        .attr("r", 4.5);

        node.append("text")
        .attr("dx", function(d) { return d.children ? -8 : 8; })
        .attr("dy", 3)
        .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
        .text(function(d) { return d.name; });
        });

        d3.select(self.frameElement).style("height", height + "px");
    <% end %>

这是我的(未缩小的)JSON 字符串:

Here is my (unminified) JSON string:

var mystring = '{
    "name": "Product",
    "properties": {
        "id": {
            "type": "number",
            "description": "Product identifier",
            "required": true
        },
        "name": {
            "type": "string",
            "description": "Name of the product",
            "required": true
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "required": true
        },
        "tags": {
            "type": "array",
            "items": {
                "type": "string"
            }
        },
        "stock": {
            "type": "object",
            "properties": {
                "warehouse": {
                    "type": "number"
                },
                "retail": {
                    "type": "number"
                }
            }
        }
    }
}';

我尝试过的事情:

  1. 缩小 JSON 使其仅作为一行输入(无效)

  1. minifying the JSON so it's inputted as just one line (no effect)

在字符串上运行 JSON.parse(mystring)

running JSON.parse(mystring) on the string

查看 D3 文档并在谷歌上搜索修改以下函数以接受字符串而不是文件路径的方法:

looking through the D3 documentation and and googling for a way to modify the following function to accept a string instead of a file path:

d3.json("/assets/flare.json", function(root) {
        var nodes = cluster.nodes(root),
        links = cluster.links(nodes);

推荐答案

首先,让我们看看 d3.json 做了什么.

First, lets look at what d3.json does.

d3.json("/assets/flare.json", function(root) {
    // code that uses the object 'root'
});

这会从服务器加载文件 /assets/flare.json,将内容解释为 JSON 并将结果对象作为 root 参数传递给匿名函数.

This loads the file /assets/flare.json from the server, interprets the contents as JSON and passes the resulting object as the root argument to the anonymous function.

如果您已经有一个 JSON 对象,则不需要使用 d3.json 函数 - 您可以直接使用该对象.

Where you already have a JSON object, you don't need to use the d3.json function - you can just use the object directly.

var root = {
   "name": "flare",
   "children": [
     ...
   ]
};
// code that uses the object 'root'

如果对象表示为字符串,则可以使用JSON.parse来获取对象:

If the object is represented as a string, then you can use JSON.parse to get the object:

var myString = '{"name": "flare","children": [ ... ] }';
var root = JSON.parse(mystring);
// code that uses the object 'root'

其次,让我们看看 d3.layout.cluster 对您的数据的期望.根据文档:

Second, lets look at what d3.layout.cluster expects of your data. As per the docs:

...默认子访问器假设每个输入数据都是一个带有子数组的对象...

... the default children accessor assumes each input data is an object with a children array ...

换句话说,您的数据需要采用以下形式:

In other words, you data needs to be of the form:

var mystring = '{
    "name": "Product",
    "children": [
        {
            "name": "id",
            "type": "number",
            "description": "Product identifier",
            "required": true
        },
        ...
        {
            "name": "stock",
            "type": "object",
            "children": [
                {
                    "name: "warehouse",
                    "type": "number"
                },
                {
                    "name": "retail",
                    "type": "number"
                }
            ]
        }
    ]
}

这篇关于从 JSON 字符串而不是 JSON 文件渲染 D3 图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆