JavaScript递归处理JSON数据:实现标准格式输出
JavaScript递归处理JSON数据:实现标准格式输出
本文将介绍如何使用JavaScript递归函数处理JSON数据,将其转换为以下标准格式:
interface BaseType {
key: string;
name?: string;
type?: string;
required?: boolean;
demo?: string;
description?: string;
children?: BaseType[];
}
以下是一个示例函数:
function processJSON(jsonData) {
const result = [];
for (const key in jsonData) {
const value = jsonData[key];
const baseType = { key: key };
if (typeof value === 'object' && value !== null) {
baseType.children = processJSON(value);
} else {
baseType.type = typeof value;
baseType.demo = JSON.stringify(value);
}
result.push(baseType);
}
return result;
}
使用示例:
const jsonData = {
key1: 'value1',
key2: {
nestedKey1: 'nestedValue1',
nestedKey2: {
nestedNestedKey1: 'nestedNestedValue1'
}
},
key3: 123
};
const result = processJSON(jsonData);
console.log(result);
输出结果:
[
{
'key': 'key1',
'type': 'string',
'demo': ''value1''
},
{
'key': 'key2',
'children': [
{
'key': 'nestedKey1',
'type': 'string',
'demo': ''nestedValue1''
},
{
'key': 'nestedKey2',
'children': [
{
'key': 'nestedNestedKey1',
'type': 'string',
'demo': ''nestedNestedValue1''
}
]
}
]
},
{
'key': 'key3',
'type': 'number',
'demo': '123'
}
]
**注意:**以上示例中的处理逻辑仅适用于简单的JSON数据,如果JSON数据包含复杂的嵌套结构或特殊情况,可能需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/SGH 著作权归作者所有。请勿转载和采集!