json-editor-parser.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. export const parser = (input: string | string[]) => {
  2. try {
  3. if (typeof input !== "object") input = JSON.parse(input);
  4. if (!Array.isArray(input)) input = [input];
  5. const extract = (
  6. os: string[] | object[] | null,
  7. nextId = (
  8. (id) => () =>
  9. String(++id)
  10. )(0)
  11. ) => {
  12. if (!os) return [];
  13. return [os].flat().map((o) => ({
  14. id: nextId(),
  15. text: Object.fromEntries(
  16. Object.entries(o).filter(
  17. ([k, v]) => !Array.isArray(v) && !(v instanceof Object)
  18. )
  19. ),
  20. children: Object.entries(o)
  21. .filter(([k, v]) => Array.isArray(v) || typeof v === "object")
  22. .flatMap(([k, v]) => [
  23. {
  24. id: nextId(),
  25. text: k,
  26. children: extract(v, nextId),
  27. },
  28. ]),
  29. }));
  30. };
  31. const relationships = (xs: { id: string; children: never[] }[]) => {
  32. return xs.flatMap(({ id: to, children = [] }) => [
  33. ...children.map(({ id: from }) => ({
  34. id: `e${from}-${to}`,
  35. from,
  36. to,
  37. })),
  38. ...relationships(children),
  39. ]);
  40. };
  41. const flatten = (xs: { id: string; children: never[] }[]) =>
  42. xs.flatMap(({ children, ...rest }) => [rest, ...flatten(children)]);
  43. const res = extract(input);
  44. return [...flatten(res), ...relationships(res)];
  45. } catch (error) {
  46. console.error("An error occured while parsin JSON data!");
  47. return [];
  48. }
  49. };