Javascript 如何获取 JSON 对象中的键值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8711580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:11:07  来源:igfitidea点击:

How to get the key value in JSON object?

javascriptjson

提问by selladurai

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

如何使用 JavaScript 获取 JSON 对象中的键值和对象的长度。
例如:

[
  {
    "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?

这里,这个数组的长度是 3。为了获取值很好([0].amount),在索引中[0]它有 3 个名称值对。
所以,我需要得到名字(比如数量或工作......总共四个名字),并计算有多少个名字?

采纳答案by T.J. Crowder

First off, you're not dealing with a "JSON object." You're dealing with a JavaScript object. JSON is a textualnotation, 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.)

首先,您不是在处理“JSON 对象”。您正在处理一个 JavaScript 对象。JSON 是一种文本表示法,但如果您的示例代码有效 ( [0].amount),则您已经将该表示法反序列化为 JavaScript 对象图。(您引用的内容根本不是有效的 JSON;在JSON 中,键必须用双引号括起来。您引用的是 JavaScript 对象文字,它是 JSON 的超集。)

Here, length of this array is 2.

这里,这个数组的长度是 2。

No, it's 3.

不,是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:

如果您使用的环境完全支持 ECMAScript5,则可以使用Object.keys( spec| MDN) 将其中一个对象的可枚举键作为数组获取。如果没有(或者如果您只想遍历它们而不是获取它们的数组),您可以使用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..inloop 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 ownkeys (and not the keys of its prototype) by adding a hasOwnPropertycall in there:

由于您正在处理原始对象,因此上面的for..in循环很好(除非有人犯了乱用 with 的罪Object.prototype,但我们假设没有)。但是,如果您想要键的对象也可以从其原型继承可枚举属性,则可以通过在其中添加调用来将循环限制为仅对象自己的键(而不是其原型的键)hasOwnProperty

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

回答by Anand

Json are basically represented as associate array in Javascript. Just need to loop over them to either read key or value

Json 在 Javascript 中基本上表示为关联数组。只需要遍历它们即可读取键或值

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

    //read key
    for (var key in JsonObj) {
       console.log(key);
       console.log(JsonObj[key]);
   }

回答by Jaseem

You may need:

你可能需要:

Object.keys(JSON[0]);

To get something like:

得到类似的东西:

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


Note: Your JSON is invalid.

注意:您的 JSON 无效。

回答by Mansuri Nurulhuda

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)

回答by Savyasachi

You can simply traverse through the object and return if found the match 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;
        }
    }
 }

回答by Matt

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

当您解析 JSON 表示时,它将变成一个 JavaScript对象数组

Because of this, you can use the .lengthpropertyof the JavaScript array to see how many elements are contained, and use a forloop to enumerate it.

因此,您可以使用JavaScript 数组的.length属性来查看包含多少元素,并使用for循环来枚举它。