function generateGoStructFromJSON(jsonObject, structName = 'Data') {
let goStruct = `type ${structName} struct {\n`;
let subStruct = '';
for (const key in jsonObject) {
const value = jsonObject[key];
let valueType = 'string';
if (typeof value === 'number') {
valueType = 'int';
} else if (Array.isArray(value)) {
if (value.length > 0 && typeof value[0] === 'object') {
const subStructName = key.charAt(0).toUpperCase() + key.slice(1) + '';
subStruct += generateGoStructFromJSON(value[0], subStructName);
valueType = `[]${subStructName}`;
} else {
valueType = `[]${determineArrayType(value[0])}`;
}
} else if (typeof value === 'object') {
const subStructName = key.charAt(0).toUpperCase() + key.slice(1) + '';
subStruct += generateGoStructFromJSON(value, subStructName);
valueType = subStructName;
}
goStruct += ` ${key.charAt(0).toUpperCase() + key.slice(1)} ${valueType} \`json:"${key}"\`\n`;
}
goStruct += '}\n\n';
goStruct += subStruct;
return goStruct;
}
function determineArrayType(value) {
if (typeof value === 'number') {
return 'int';
} else {
return 'string';
}
}
document.addEventListener('DOMContentLoaded', function () {
const jsonInput = document.getElementById('jsonInput');
const generateButton = document.getElementById('generateButton');
const output = document.getElementById('output');
generateButton.addEventListener('click', function () {
const jsonString = jsonInput.value;
try {
const jsonObject = JSON.parse(jsonString);
const goStruct = generateGoStructFromJSON(jsonObject, 'Data');
output.textContent = goStruct;
} catch (error) {
output.textContent = 'Invalid JSON: ' + error.message;
}
});
});
コメント
コメントを投稿