diff --git a/src/utils/jsonParser.ts b/src/utils/jsonParser.ts index 84592e0b21b..faf1ede4a64 100644 --- a/src/utils/jsonParser.ts +++ b/src/utils/jsonParser.ts @@ -1,4 +1,4 @@ -import { Node, parseTree } from "jsonc-parser"; +import { Node, NodeType, parseTree } from "jsonc-parser"; const calculateSize = ( text: string | [string, string][], @@ -74,6 +74,25 @@ export const parser = (jsonStr: string, isFolded = false) => { ]; }; + const isPrimitiveOrNullType = (type?: NodeType) => { + return ( + type === "boolean" || + type === "string" || + type === "number" || + type === "null" + ); + }; + + const alignChildren = (a: Node, b: Node) => { + if ( + isPrimitiveOrNullType(a?.children?.[1]?.type) && + !isPrimitiveOrNullType(b?.children?.[1]?.type) + ) { + return -1; + } + return 0; + }; + let parentName: string = ""; let bracketOpen: { id: string; type: string }[] = []; let objectsFromArray: number[] = []; @@ -203,26 +222,28 @@ export const parser = (jsonStr: string, isFolded = false) => { } else if (parentType === "array") { objectsFromArray = [...objectsFromArray, objectsFromArrayId++]; } - children.forEach((branch, index, array) => { - if (array[index + 1]) { - traverse( - branch, - type, - bracketOpen[bracketOpen.length - 1] - ? bracketOpen[bracketOpen.length - 1].id - : undefined, - array[index + 1].type - ); - } else { - traverse( - branch, - type, - bracketOpen[bracketOpen.length - 1] - ? bracketOpen[bracketOpen.length - 1].id - : undefined - ); + (type === "object" ? children.sort(alignChildren) : children).forEach( + (branch, index, array) => { + if (array[index + 1]) { + traverse( + branch, + type, + bracketOpen[bracketOpen.length - 1] + ? bracketOpen[bracketOpen.length - 1].id + : undefined, + array[index + 1].type + ); + } else { + traverse( + branch, + type, + bracketOpen[bracketOpen.length - 1] + ? bracketOpen[bracketOpen.length - 1].id + : undefined + ); + } } - }); + ); if (type !== "property") { // when children end