我可以使用 d3.json 处理类似于 json 格式的字符串吗?



我在网上搜索过,而大多数人直接从 url 或本地文件夹中读取 .json 文件 喜欢

console.log("before csv ");
d3.csv("cities.csv", function(data) {console.log(data)});
console.log("before json");
d3.json("flare.json",function(error,data2) {console.log(error, data2)});

虽然目前我的要求是我有一个字符串,它是 JSON 格式的,比如

{"nodes": [
{"id": "Myriel"},
{"id": "Napoleon"},
{"id": "Mlle.Baptistine"},
{"id": "Mme.Magloire"},
{"id": "CountessdeLo"},
{"id": "Geborand"},
{"id": "Champtercier"},
{"id": "Cravatte"},
{"id": "Count"},
{"id": "OldMan"},
{"id": "Labarre"},
{"id": "Valjean"},
{"id": "Marguerite"},
{"id": "Mme.deR"}
]}

有没有一种方法可以直接将此字符串处理为从 .json 或.csv文件读取的数据?

D3 仅适用于 JS 对象,d3.json 只是从外部文件加载对象的方法。因此,如果您不需要从外部文件加载数据,请不要使用 d3.json。

您可以执行以下操作的方法之一:

var jsonObj = JSON.parse(data);

你可以直接使用JSON.parse函数将字符串解析为 JSON,而无需像这样使用 d3 -

var json = JSON.parse(yourString);

最新更新