简体   繁体   中英

How can I get the key value in a JSON object?

How do I get the key value in a JSON object and the 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 three name value pairs.

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

JSON content is basically represented as an associative array in JavaScript. You just need to loop over them to either read the key or the value:

    var JSON_Obj = { "one":1, "two":2, "three":3, "four":4, "five":5 };

    // Read key
    for (var key in JSON_Obj) {
       console.log(key);
       console.log(JSON_Obj[key]);
   }

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 ( spec | MDN ) 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;
  }
}

You may need:

Object.keys(JSON[0]);

To get something like:

[ 'amount', 'job', 'month', 'year' ]

Note: Your JSON is invalid.

Try out this

var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)

//Array Object

str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

You can simply traverse through the object and return if a match is found.

Here is the code:

returnKeyforValue : function() {
    var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
        for (key in JsonObj) {
        if(JsonObj[key] === "Keyvalue") {
            return key;
        }
    }
}

When you parse the JSON representation , it'll become a JavaScript array of objects.

Because of this, you can use the .length property of the JavaScript array to see how many elements are contained, and use a for loop to enumerate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM