Reputation: 319
I am referring to this example: http://bl.ocks.org/mbostock/1153292 , specifically to these beautiful lines of code:
var links = [
{source: "Microsoft", target: "Amazon", type: "licensing"},
...
{source: "Nokia", target: "Qualcomm", type: "suit"}
];
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
I'd like to know what data format 'var links' here has, and how I would parse the following java string (with essentially the same content)
String someLinks = "[{source: \"Microsoft\", target: ... }, ...]"
into something equal to the javascript 'var links' above, from which I can then create the graph.
I've tried
var links = JSON.parse( string );
But that doesn't do the job... 'var links' doesn't seem to be JSON? EDIT: Or should I use a different java format, e.g. some kind of Array? (Doesn't have to be a String)
Upvotes: 1
Views: 673
Reputation: 37073
Your value in String someLinks
is no valid JSON. It lacks the quotes on the attribute names. JSON is more pedantic than javascript itself.
JSON.parse('[{"source":"A"},{"source":"B"}]')
will work (note the "
around source
.
Also you should avoid writing "protocols" by hand. If you need to build a JSON string in javascript, you can use
JSON.stringify([{source:'A'},{source:'B'}])
Note that JSON e.g. also escapes /
for security reasons. An oversight like this can quickly end in errors or worse.
Upvotes: 1
Reputation: 5144
I believe this is JSON in a string. Since JSON is simply JavaScript, you might be able to simply "run" the code to create the corresponding data structure. So try
var links = eval(someLinks)
Even though I have the suspicion if we take a step back, things might be handled differently and you wouldn't need eval
in the first place (since it's generally considered bad style)
Upvotes: 0