json-editor-parser.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @param {never[] | Object} input
  3. * @returns {import("react-flow-renderer").FlowElement[]}
  4. */
  5. export const parser = (input) => {
  6. try {
  7. input = JSON.parse(input);
  8. if (!Array.isArray(input)) input = [input];
  9. const extract = (
  10. os,
  11. nextId = (
  12. (id) => () =>
  13. String(++id)
  14. )(0)
  15. ) => {
  16. if (!os) return [];
  17. return [os].flat().map((o) => ({
  18. id: nextId(),
  19. data: {
  20. label: Object.fromEntries(
  21. Object.entries(o).filter(([k, v]) => !Array.isArray(v))
  22. ),
  23. },
  24. position: { x: 0, y: 0 },
  25. type: "special",
  26. children: Object.entries(o)
  27. .filter(([k, v]) => Array.isArray(v) || typeof v === "object")
  28. .flatMap(([k, v]) => [
  29. {
  30. id: nextId(),
  31. data: { label: k },
  32. position: { x: 0, y: 0 },
  33. children: extract(v, nextId),
  34. type: "special",
  35. },
  36. ]),
  37. }));
  38. };
  39. const relationships = (xs) =>
  40. xs.flatMap(({ id: target, children = [] }) => [
  41. ...children.map(({ id: source }) => ({
  42. id: `e${source}-${target}`,
  43. source,
  44. target,
  45. })),
  46. ...relationships(children),
  47. ]);
  48. const flatten = (xs) =>
  49. xs.flatMap(({ children, ...rest }) => [rest, ...flatten(children)]);
  50. const res = extract(input);
  51. return [...flatten(res), ...relationships(res)];
  52. } catch (error) {
  53. console.error("An error occured while parsin JSON data!", error.stack);
  54. return Array;
  55. }
  56. };