I am an old-school C++ programmer - trying to get to grips with Postman, JSON, REST APIs, etc, and struggling..
I am trying to write a Postman test to visualize some JSON response data - which I would like to show in a table format with some merged key names as column headings.
The problem is that the number of data items in a response can vary and the key names can also vary - depending on the input parameters.
So say, for the following JSON which has two data items:
{
"data": [
{
"input": [
{
"value": "ABC",
"identifierType": "a1"
}
],
"output": [
{
"value": "BT",
"identifierType": "b1",
"name": "BT GROUP",
"status": "Active",
"classification": "Ordinary"
}
]
},
{
"input": [
{
"value": "BCD",
"identifierType": "a1"
}
],
"output": [
{
"value": "EFG",
"identifierType": "b1",
"name": "SIEMENS",
"status": "Active",
"classification": "Ordinary"
}
]
}
]
}
I want to end up with a collection containing column headings that looks something like this: [“Input value”, “Input identifierType”,“Output value”,“Output identifierType”,“Output name”,“Output status”,“Output classification”]
I can get part of the way with something like the following:
function parseData(response, host) {
const results = response.map(elem => (
[
elem.input[0].value,
elem.input[0].identifierType,
elem.output[0].value,
elem.output[0].identifierType,
elem.output[0].name,
elem.output[0].status,
elem.output[0].classification,
]
));
const headers = [];
for (const key in response[0].input[0]){
headers.push(`Input ${key}`)
}
for (const key in response[0].output[0]){
headers.push(`Output ${key}`)
}
return [results, headers]
}
This gives me the desired headers: [“Input value”, “Input identifierType”,“Output value”,“Output identifierType”,“Output name”,“Output status”,“Output classification”]
However, I want to make this more general i.e. not have to specify input[0] and output[0] in the for loops - as these key names could differ for different query responses.
I did ask this question on the Postman forums and someone helpfully provided a code snippet that allows me to extract the 'input' and 'output' names.
for (const _outer in response[0]) {
for (const _inner in _outer) {
for (const key in _inner) {
headers.push(`${_outer} ${key}`)
}
}
}
But that only gives me: ["input 0", "input 0", "input 0", "input 0", "input 0", "output 0' …] for the headers. For some reason I cannot access the inner keys such as value, name, identifierType, status etc
Can someone please suggest where the above is going wrong / how to get what I am after? Thanks.