While I am able to properly parse this payload if I specify the keys via bracket notation, how could you parse it dynamically?
{
"name": "Demo User",
"birthday": "January 1st",
"hobbies":
{
"morning": "coding",
"afternoon": "kewl kids stuff",
"nighttime": "random"
},
"date": "June 25th"
}
What I mean by that is hobbies might not be there, or another field such as 'favorite foods' might exist, which could be an array, or an object.
This scenario has caused me a lot of frustration over the last couple months, and I'm trying to see if anyone can explain to me how to successfully parse it, dynamically.
I found a recursive 'walk' approach that is no longer erroring, but it's returning the first thing it comes across for every iteration.
var data = require("./demo.json");
//data = JSON.stringify(data);
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(data);
Basic on what I found, data is being imported as JSON, and if I stringify it, it becomes a string (obviously).
Default
{ name: 'Demo User',
birthday: 'January 1st',
hobbies:
{ morning: 'coding',
afternoon: 'kewl kids stuff',
nighttime: 'random' },
date: 'June 25th' }
Stringify
{"name":"Demo User","birthday":"January 1st","hobbies":{"morning":"coding","afternoon":"kewl kids stuff","nighttime":"random"},"date":"June 25th"}
Both are similar, but the only difference on output is it spamming D
X times (Being the first value, I'm thinking?) or spamming {
X times (Being the first value of the string?
I've tried a much more basic approach of
var data = require("./demo.json");
for (var key in data){
console.log(key + ':' + data[key]);
}
Which works fine, but as expected, hobbies is returning [object Object]
since I am not iterating through it. I could go through hobbies
, but again - I don't know if it will exist.
Welcome any input - Generic question, but a process that has caused me a lot of frustration on different projects over last few months.
UPDATE
My vagueness is causing, rightfully-so, confusion.
Let's say my objective is to turn this JSON Payload into a CSV. I need every key for the headers, and every value to be a row under said header. My issue is, as I iterate through it, I end up with the highest-level objects correctly converted. Then I end up with an object Object column with no data.
For this exact example, let's say my goal is to convert the JSON into
name, birthday, hobbies/morning, hobbies/afternoon, hobbies/nighttime, data
Demo User, January 1st, coding, kewl kids stuff, random, June 25th
Update # 2
Additional array
variant.
I would expect
{
...
"hobbies":
{
"morning": "coding",
"afternoon": "kewl kids stuff",
"nighttime": "random"
},
...
}
To output
hobbies/morning, hobbies/afternoon, hobbies/nighttimes
I would expect
{
...
"hobbies": ["coding", "kewl kids stuff", "coding"]
...
}
To output one column
hobbies
with quote-enclosed items
"coding, kewl kids stuff, coding"