json-editor-parser.js 1.7 KB

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