-1

ex 1:

data =`{"serialNo": "1","items":{"item":[{"RECORDNO": "2", "amount" = 40},{"RECORDNO": "3","amount" = 40}]},}`

ex 2:

data=`{"serialNo": "2","items":{"item":{"RECORDNO": "4841","amount" = 40}}}`

The above is an example of a JSON value returned from an API call. The type is a little inconsistent as seen above. If the item has only one record, the json type is an object. If the item has multiple records the json type is an array. I am interested in extracting the item and process it.

const vals = [data.items.item][0];
vals.forEach(val => {
  // do something
});

The code above works well for ex 1 but fails for ex2 as it's not of the type array.
What would be an easiest way to extract the item as an array to process easily.

Phil
  • 157,677
  • 23
  • 242
  • 245
Valkyrie
  • 189
  • 1
  • 1
  • 15
  • 1
    That ain't JSON – Phil Aug 16 '22 at 23:06
  • `"amount" = 40` isn't JSON. Ditto for the dangling comma. Please show your actual response and how you're parsing this into `data`. – ggorlen Aug 16 '22 at 23:09
  • This is typical of APIs that support both XML and JSON where XML is the primary result type and the JSON is just hacked together from that – Phil Aug 16 '22 at 23:10

1 Answers1

-1

Just check whether the property is an array with Array.isArray:

const data={serialNo:"1",items:{item:[{RECORDNO:"2",amount:40},{RECORDNO:"3",amount:40}]}};

const data2={serialNo:"2",items:{item:{RECORDNO:"4841",amount:40}}};

function process(res){
  const { item }  = res.items;
  if(Array.isArray(item)){
    console.log(item.map(JSON.stringify))
  } else {
    console.log(item)
  }
}

process(data)
process(data2)
Spectric
  • 30,714
  • 6
  • 20
  • 43