|
<!DOCTYPE html> |
|
<html lang="en"> |
|
|
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>JSON Viewer with Selector</title> |
|
<style> |
|
body { |
|
font-family: Arial, sans-serif; |
|
margin: 20px; |
|
} |
|
|
|
.json-container { |
|
border: 1px solid #ccc; |
|
padding: 10px; |
|
margin-bottom: 10px; |
|
} |
|
|
|
.json-key { |
|
font-weight: bold; |
|
} |
|
</style> |
|
</head> |
|
|
|
<body> |
|
|
|
<form id="jsonSelectorForm"> |
|
<label for="jsonSelector">Choose Data to Display:</label> |
|
<select id="jsonSelector" onchange="updateDisplay()"></select> |
|
</form> |
|
|
|
<div id="jsonDisplayContainer"> |
|
|
|
</div> |
|
|
|
<script> |
|
let jsonDataArray = []; |
|
|
|
async function fetchData() { |
|
try { |
|
const response = await fetch('characters.json'); |
|
if (!response.ok) { |
|
throw new Error(`Failed to fetch data. Status: ${response.status}`); |
|
} |
|
const rawData = await response.text(); |
|
const lines = rawData.split('\n').filter(Boolean); |
|
|
|
jsonDataArray = lines.map(line => JSON.parse(line)); |
|
} catch (error) { |
|
console.error('Fetch error:', error.message); |
|
} |
|
} |
|
|
|
function populateDropdown() { |
|
const selector = document.getElementById('jsonSelector'); |
|
|
|
jsonDataArray.forEach((_, index) => { |
|
const option = document.createElement('option'); |
|
option.value = index; |
|
option.text = `Object ${index + 1}`; |
|
selector.add(option); |
|
}); |
|
} |
|
|
|
function updateDisplay() { |
|
const selector = document.getElementById('jsonSelector'); |
|
const displayContainer = document.getElementById('jsonDisplayContainer'); |
|
const selectedIndex = selector.value; |
|
|
|
if (selectedIndex >= 0) { |
|
const jsonObject = jsonDataArray[selectedIndex]; |
|
|
|
|
|
displayContainer.innerHTML = `<div class="json-container">${renderJson(jsonObject)}</div>`; |
|
} else { |
|
displayContainer.innerHTML = ''; |
|
} |
|
} |
|
|
|
function renderJson(obj) { |
|
const orderedKeys = ['name', 'age', 'gender', "race", "education", "occupation", "expertise", "hobby", "positive_personality", "negative_personality"]; |
|
let html = ''; |
|
|
|
orderedKeys.forEach(key => { |
|
if (key in obj) { |
|
html += `<div><span class="json-key">${key}:</span> ${obj[key]}</div>`; |
|
} |
|
}); |
|
|
|
for (const [key, value] of Object.entries(obj)) { |
|
if (!orderedKeys.includes(key)) { |
|
html += `<div><span class="json-key">${key}:</span> ${value}</div>`; |
|
} |
|
} |
|
|
|
return html; |
|
} |
|
|
|
|
|
async function initializePage() { |
|
await fetchData(); |
|
populateDropdown(); |
|
updateDisplay(); |
|
} |
|
|
|
initializePage(); |
|
</script> |
|
|
|
</body> |
|
|
|
</html> |
|
|