json-editor-parser.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { defaultValue } from "src/pages/editor/JsonEditor";
  2. /**
  3. * @param {never[] | Object} input
  4. * @returns {import("react-flow-renderer").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(([k, v]) => !Array.isArray(v))
  23. ),
  24. },
  25. position: { x: 0, y: 0 },
  26. type: "special",
  27. children: Object.entries(o)
  28. .filter(([k, v]) => Array.isArray(v) || typeof v === "object")
  29. .flatMap(([k, v]) => [
  30. {
  31. id: nextId(),
  32. data: { label: k },
  33. position: { x: 0, y: 0 },
  34. children: extract(v, nextId),
  35. type: "special",
  36. },
  37. ]),
  38. }));
  39. };
  40. const relationships = (xs) =>
  41. xs.flatMap(({ id: target, children = [] }) => [
  42. ...children.map(({ id: source }) => ({
  43. id: `e${source}-${target}`,
  44. source,
  45. target,
  46. })),
  47. ...relationships(children),
  48. ]);
  49. const flatten = (xs) =>
  50. xs.flatMap(({ children, ...rest }) => [rest, ...flatten(children)]);
  51. const res = extract(input);
  52. return [...flatten(res), ...relationships(res)];
  53. } catch (error) {
  54. console.error("An error occured while parsin JSON data!", error.stack);
  55. return Array;
  56. }
  57. };