Given the following JSON file:
[{
"id": 34466,
"name": "Item 3",
"location_id": 34467,
"types": [
"B",
"C"
],
"location": "U Quad",
"region_id": 1023,
"last_contact": "2023-12-26"
},
{
"id": 34258,
"name": "Item 1",
"location_id": 33975,
"day": 0,
"time": "20:30",
"time_formatted": "8:30 pm",
"types": [
"D"
],
"location": "S Quad",
"group": "Group ID: 000105941",
"phone": "8475551221",
"last_contact": "2020-11-18"
},
{
"id": 34259,
"name": "Item 2",
"location_id": 33970,
"day": 0,
"time": "20:30",
"time_formatted": "8:30 pm",
"types": [
"D",
"ONL"
],
"location": "T Quad",
"group": "Group ID: 000105941",
"phone": "8475551222",
"last_contact": "2020-11-18"
}
]
I am trying to simply convert from JSON and convert the data to a CSV file. The problem I am having is that since the records have optional fields, the export contains only the fields the first record has for all exported records. Thus, in this case above, the output omits day, group, and time fields from the last 2 records:
My code is:
$json = (get-content "test.json"| ConvertFrom-Json) | ConvertTo-Csv -NoTypeInformation | out-file "test-output.csv"
I have noticed if Items 1 and 2 appear first in the JSON, I get all fields in the CSV file.
Is there a way to force the CSV output to contain the fields of the most complete records? I suppose I could sort them to put the most complete on top or specifically enumerate all fields using a Select-Object, but it seemed to me there must be an easier way.
Thanks in advance.
