selladurai selladurai - 3 months ago 8
JSON Question

How to get the key value in JSON object?

How to get the key valu in JSON object and length of the object using JavaScript.

For Example:

[
{
"amount": " 12185",
"job": "GAPA",
"month": "JANUARY",
"year": "2010"
},
{
"amount": "147421",
"job": "GAPA",
"month": "MAY",
"year": "2010"
},
{
"amount": "2347",
"job": "GAPA",
"month": "AUGUST",
"year": "2010"
}
]


Here, length of this array is 3. For getting value is fine
([0].amount)
, in index
[0]
it has 3 name value pair.
So, I need to get the name (like amount or job... totally four name) and also to count how many names are there?

Answer

First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textual notation, but if your example code works ([0].amount), you've already deserialized that notation into a JavaScript object graph. (What you've quoted isn't valid JSON at all; in JSON, the keys must be in double quotes. What you've quoted is a JavaScript object literal, which is a superset of JSON.)

Here, length of this array is 2.

No, it's 3.

So, i need to get the name (like amount or job... totally four name) and also to count how many names are there?

If you're using an environment that has full ECMAScript5 support, you can use Object.keys to get the enumerable keys for one of the objects as an array. If not (or if you just want to loop through them rather than getting an array of them), you can use for..in:

var entry;
var name;
entry = array[0];
for (name in entry) {
    // here, `name` will be "amount", "job", "month", then "year" (in no defined order)
}

Full working example:

(function() {

  var array = [
    {
    amount: 12185,
    job: "GAPA",
    month: "JANUARY",
    year: "2010"
    },
    {
    amount: 147421,
    job: "GAPA",
    month: "MAY",
    year: "2010"
    },
    {
    amount: 2347,
    job: "GAPA",
    month: "AUGUST",
    year: "2010"
    }
  ];

  var entry;
  var name;
  var count;

  entry = array[0];

  display("Keys for entry 0:");
  count = 0;
  for (name in entry) {
    display(name);
    ++count;
  }
  display("Total enumerable keys: " + count);

  // === Basic utility functions

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }

})();

Since you're dealing with raw objects, the above for..in loop is fine (unless someone has committed the sin of mucking about with Object.prototype, but let's assume not). But if the object you want the keys from may also inherit enumerable properties from its prototype, you can restrict the loop to only the object's own keys (and not the keys of its prototype) by adding a hasOwnProperty call in there:

for (name in entry) {
  if (entry.hasOwnProperty(name)) {
    display(name);
    ++count;
  }
}