47 lines
1.4 KiB
TypeScript
Executable file
47 lines
1.4 KiB
TypeScript
Executable file
/**
|
|
* File operations and JSON traversal utilities
|
|
*/
|
|
|
|
import type { StringLocation } from './types.js';
|
|
|
|
/**
|
|
* Extract all string values from a JSON object with their paths
|
|
*/
|
|
export function extractStrings(obj: unknown, path = ''): StringLocation[] {
|
|
const results: StringLocation[] = [];
|
|
|
|
if (typeof obj === 'string' && obj.length > 10) {
|
|
results.push({ path, value: obj });
|
|
} else if (Array.isArray(obj)) {
|
|
obj.forEach((item, index) => {
|
|
results.push(...extractStrings(item, `${path}[${index}]`));
|
|
});
|
|
} else if (typeof obj === 'object' && obj !== null) {
|
|
for (const [key, value] of Object.entries(obj)) {
|
|
if (key.startsWith('_')) continue;
|
|
results.push(...extractStrings(value, path ? `${path}.${key}` : key));
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/**
|
|
* Set a value at a nested path in an object
|
|
*/
|
|
export function setNestedValue(obj: Record<string, unknown>, path: string, value: string): void {
|
|
const parts = path.replace(/\[(\d+)\]/g, '.$1').split('.');
|
|
let current: unknown = obj;
|
|
|
|
for (let i = 0; i < parts.length - 1; i++) {
|
|
const part = parts[i];
|
|
if (current && typeof current === 'object') {
|
|
current = (current as Record<string, unknown>)[part];
|
|
}
|
|
}
|
|
|
|
if (current && typeof current === 'object') {
|
|
const lastPart = parts[parts.length - 1];
|
|
(current as Record<string, unknown>)[lastPart] = value;
|
|
}
|
|
}
|