I’m trying to develop a new plugin that visualizes attack trees, at the moment the goal is to be able to draw nodes and links reading the nodes positions from a json file.
I tried to put the file in public/assets/file.json directory. When I try to load the file I’m getting an error.
Plugin code
import React, { useEffect, useRef, useState } from 'react';
import * as d3 from 'd3';
// Percorso del file JSON
const DATA_URL = 'plugins/attack_tree/public/assets/circles.json'; // Sostituisci con il percorso effettivo
export const Circle: React.FC = () => {
const svgRef = useRef<SVGSVGElement | null>(null);
const [circles, setCircles] = useState<{ id: number; x: number; y: number; r: number; color: string }[]>([]);
useEffect(() => {
// Carica il file JSON
d3.json(DATA_URL)
.then((data) => {
if (Array.isArray(data)) {
setCircles(data);
} else {
console.error('Il file JSON deve essere un array.');
}
})
.catch((error) => console.error('Errore nel caricamento del file JSON:', error));
}, []);
useEffect(() => {
if (svgRef.current && circles.length > 0) {
const svg = d3.select(svgRef.current);
// Dimensioni dell'SVG
const width = 400;
const height = 400;
// Pulisci eventuali elementi esistenti
svg.selectAll('*').remove();
// Imposta la dimensione e il centro dell'SVG
svg.attr('width', width).attr('height', height);
// Disegna le linee tra i cerchi
for (let i = 0; i < circles.length; i++) {
const start = circles[i];
const end = circles[(i + 1) % circles.length]; // Connette ogni cerchio al successivo, chiudendo il triangolo
svg
.append('line')
.attr('x1', start.x)
.attr('y1', start.y)
.attr('x2', end.x)
.attr('y2', end.y)
.attr('stroke', 'black')
.attr('stroke-width', 2);
}
// Disegna i cerchi
circles.forEach((circle) => {
svg
.append('circle')
.attr('cx', circle.x)
.attr('cy', circle.y)
.attr('r', circle.r)
.attr('fill', circle.color);
});
}
}, [circles]);
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<svg ref={svgRef}></svg>
</div>
);
};
**JSON file**
[
{ “id”: 1, “x”: 200, “y”: 100, “r”: 30, “color”: “steelblue” },
{ “id”: 2, “x”: 150, “y”: 250, “r”: 30, “color”: “orange” },
{ “id”: 3, “x”: 250, “y”: 250, “r”: 30, “color”: “green” }
]
Error
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data