Issue report: sort template key first in config dump (#31079)
This commit is contained in:
parent
0a96b3fd54
commit
8b2c540741
2 changed files with 34 additions and 6 deletions
|
|
@ -107,6 +107,26 @@ describe("formatJson", () => {
|
|||
{"baz":123,"foo":"bar"},
|
||||
{"id":1,"num":456,"qux":"test"}
|
||||
]
|
||||
}`);
|
||||
});
|
||||
|
||||
it("sorts template first inside nested config of array items", () => {
|
||||
const obj = {
|
||||
charger: [
|
||||
{
|
||||
config: { host: "192.168.1.1", template: "tesla" },
|
||||
name: "db:1",
|
||||
type: "template",
|
||||
id: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = formatJson(obj, ["charger"]);
|
||||
|
||||
expect(result).toBe(`{
|
||||
"charger": [
|
||||
{"id":1,"name":"db:1","type":"template","config":{"template":"tesla","host":"192.168.1.1"}}
|
||||
]
|
||||
}`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,6 +10,17 @@ function sortedEntries(obj: object): [string, any][] {
|
|||
});
|
||||
}
|
||||
|
||||
// recursively reorder keys so priority keys (e.g. template) stay first at every nesting level
|
||||
function sortedDeep(value: any): any {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(sortedDeep);
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(sortedEntries(value).map(([k, v]) => [k, sortedDeep(v)]));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function formatJson(obj: any, expandKeys: string[] = []): string {
|
||||
if (!obj || typeof obj !== "object") {
|
||||
return JSON.stringify(obj, null, 2);
|
||||
|
|
@ -31,10 +42,7 @@ export function formatJson(obj: any, expandKeys: string[] = []): string {
|
|||
valueStr = "[]";
|
||||
} else {
|
||||
const arrayItems = value.map((item) => {
|
||||
const itemStr =
|
||||
item && typeof item === "object" && !Array.isArray(item)
|
||||
? JSON.stringify(Object.fromEntries(sortedEntries(item)))
|
||||
: JSON.stringify(item);
|
||||
const itemStr = JSON.stringify(sortedDeep(item));
|
||||
return ` ${itemStr.replace(/\\n/g, "\n")}`;
|
||||
});
|
||||
valueStr = `[\n${arrayItems.join(",\n")}\n ]`;
|
||||
|
|
@ -47,7 +55,7 @@ export function formatJson(obj: any, expandKeys: string[] = []): string {
|
|||
valueStr = "{}";
|
||||
} else {
|
||||
const objItems = objEntries.map(([k, v]) => {
|
||||
const itemStr = JSON.stringify(v);
|
||||
const itemStr = JSON.stringify(sortedDeep(v));
|
||||
return ` ${JSON.stringify(k)}: ${itemStr.replace(/\\n/g, "\n")}`;
|
||||
});
|
||||
valueStr = `{\n${objItems.join(",\n")}\n }`;
|
||||
|
|
@ -55,7 +63,7 @@ export function formatJson(obj: any, expandKeys: string[] = []): string {
|
|||
}
|
||||
} else {
|
||||
// Single line for everything else
|
||||
valueStr = JSON.stringify(value).replace(/\\n/g, "\n");
|
||||
valueStr = JSON.stringify(sortedDeep(value)).replace(/\\n/g, "\n");
|
||||
}
|
||||
|
||||
lines.push(` ${JSON.stringify(key)}: ${valueStr}`);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue