0

I have a array Json like this in node js.

JSON 1

var json1= {
  bookmarkname: 'My Health Circles',
  bookmarkurl: 'http://localhost:3000/',
  bookmark_system_category: [ '22', '1' ]
}

JSON 2

var json2 = {
  bookmarkname: 'My Health Circles',
  bookmarkurl: 'http://localhost:3000/',
  bookmark_system_category:'22'
}

I tried :

var length1=json1.bookmark_system_category.length;

var length1=json2.bookmark_system_category.length;

Expected output :

l1=2;
l2=1;
1
  • FYI that's an object, not an array Commented Feb 12, 2016 at 10:49

2 Answers 2

2

length is property of string as well as array

In your second case, it is counting length of the string which is 2

May be you will need a condition:

var json1 = {
  bookmarkname: 'My Health Circles',
  bookmarkurl: 'http://localhost:3000/',
  bookmark_system_category: ['22', '1']
};
var json2 = {
  bookmarkname: 'My Health Circles',
  bookmarkurl: 'http://localhost:3000/',
  bookmark_system_category: '22'
};

var getLength = function(input) {
  if (typeof input === 'string') {
    return 'Is String';
  } else {
    return input.length;
  }
}

var length1 = getLength(json1.bookmark_system_category);
var length2 = getLength(json2.bookmark_system_category);
alert(length1);
alert(length2)

Sign up to request clarification or add additional context in comments.

Comments

0

You could use Array.isArray:

Array.isArray(json1.bookmark_system_category); // true

but this would return false for everything that isn't an array - strings, objects, null.

Here's a nifty function that will return the type of an object (in lowercase) that you can test against:

function toType(x) {
  return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

toType({}) // object
toType([]) // array
toType(null) // null
toType(0) // number
toType('bob') // string

So:

toType(json1.bookmark_system_category) // array
toType(json2.bookmark_system_category) // string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.