Last Updated: February 25, 2016
·
1.252K
· tralamazza

Parsing json responses the lazy (as in I-hate-if's) way

(Yes, I don't know how to name the tip).

Suppose you have an API call that might answer a json/js object in the following formats:

One item:

{
  foos: {
    bar: 1
  }
}

A bunch of items:

{
  foos: [{
    bar: 1
  }, {
    bar: 6
  }]
}

No item at all:

{
  foos: { }
}

BTW: This is actually quite common in API's that just translate XML to JSON.

One way to handle all 3 cases is to simply do:

var array_of_foos = [].concat(obj.foos || []);

This way array_of_foos will always contain either an empty array, or an array with all the items.

4 Responses
Add your response

Wouldn't the following do the trick too?

var arrayoffoos = obj.foos || [];

EDIT:
Ah, stupid, the concat takes care of the single value issue of course.

over 1 year ago ·

Nope, in the case where obj.foos has only 1 object, you want an array with 1 item. That would be case #1.

over 1 year ago ·

@tralamazza Just realised. Nice way of sanitising the data.

over 1 year ago ·

@guido thanks :) and may the laziness be with you too

over 1 year ago ·