<script>document.documentElement.setAttribute('lang', 'en');</script>
<section>
<style>
textarea{width:100%;}
textarea,#output{white-space:pre;font-family:monospace}
section,#output,textarea,button{background:#222;padding:.4rem .75rem;font-size:1rem;border-radius:4px;background-color:#fff;box-shadow:0 2px 3px rgba(2,2,2,0.1);border:solid 1px #c8cbd2;}
#errors{color:red}
#output{color:RoyalBlue}
#flatten{background:RoyalBlue;color:white;}
</style>
<h1 class='title'>JSON Object Flattener</h1>
<aside id="json-data-examples"></aside>
<div style="display:flex;">
<textarea rows="10" type="text" name="input" id="input"></textarea>
<button id="flatten" type="button">Flatten</button>
</div>
<p><strong>Output</strong></p>
<div id="errors"></div>
<pre id="output"></pre>
</section>
<script>
function flattenObject(obj) {
var toReturn = {};
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object') {
const flatObject = flattenObject(obj[key]);
Object.keys(flatObject).forEach(e => {
const propName = `${key}.${e}`.replace(/\.(\d+)/g, '[$1]')
toReturn[propName] = flatObject[e];
})
} else {
toReturn[key] = obj[key];
}
})
return toReturn;
}
const $$ = query => Array.from(document.querySelectorAll(query))
const $ = query => document.querySelector(query)
const $_ = id => document.getElementById(id)
$_('flatten').addEventListener('click', function () {
const readElement = $_('input')
const writeElement = $_('output')
const text = readElement.value || readElement.textContent || '{}'
try {
$_('errors').textContent = ''
writeElement.textContent = JSON.stringify(flattenObject(JSON.parse(text)), null, 2)
} catch (e) {
$_('output').textContent = ''
$_('errors').textContent = e
}
})
const exampleJSONExamples = [
`{"drinks":[{"name":"Orange juice","ingredients":"Oranges"},{"name":"Wine","ingredients":"Grapes"},{"name":"Coffee","ingredients":"Roasted Beans"}]}`,
`{"name":"Ram","age":27,"vehicles":{"car":"limousine","bike":"ktm-duke","airlines":[{"lufthansa":"Air123"},{"British airways":"Brt707"}]}}`,
`{"name":"Jungle Gym","age":25,"favorite_color":"#ffa500","gender":"male","location":{"city":"Seattle","state":"WA","citystate":"Seattle, WA"},"pets":[{"type":"dog","name":"Foo"},{"type":"cat","name":"Bar"}]}`
].map(text => JSON.stringify(JSON.parse(text), null, 2))
exampleJSONExamples.forEach((e, i) => {
const button = document.createElement('button')
Object.assign(button, {
type: 'button',
textContent: `sample data ${i + 1}`
})
button.addEventListener('click', function () {
$('textarea').value = e
$('#output').textContent = ''
$('textarea').rows = e.split('\n').length
})
$_('json-data-examples') &&
$_('json-data-examples').appendChild(button)
})
</script>