Javascript 获取 JSON 键名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38397894/
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
Get JSON key name
提问by Prince
I have the following JSON data: {"success":"You are welcome"}
that I have named json
in my JavaScript code.
我有以下 JSON 数据:{"success":"You are welcome"}
我json
在 JavaScript 代码中命名的数据。
When I want to alert You are welcome
I do json.success
. So now the problem I am facing is that, what about if I want to alert success
. Is there any way to get it?
当我想提醒时,You are welcome
我会这样做json.success
。所以现在我面临的问题是,如果我想 alert 呢success
?有什么办法可以得到吗?
回答by gurvinder372
So now the problem I am facing is that, what about if I want to alert success. Is there a need way to get it ?
所以现在我面临的问题是,如果我想提醒成功怎么办。有需要的方法吗?
If your object is
如果你的对象是
var obj = {"success":"You are welcome"};
You can get the array of keys as
您可以将键数组作为
var keys = Object.keys(obj);
and then print it as
然后将其打印为
console.log( keys[ 0 ] ); //or console.log( keys.join(",") )
var obj = {"success":"You are welcome"};
var keys = Object.keys(obj);
console.log(keys[0]);
回答by CyberBrain
You mean something like this?
你的意思是这样的?
keys = Object.keys(json_object)
key_to_use = keys[0];
回答by The Internet
Try this code
试试这个代码
alert(Object.keys({"success":"You are welcome"})[0]);
回答by Aaron
Since you're able to do json.success
, you don't have "JSON data", you have a Javascript Object. JSON, or JavaScript Object Notation, is no more than the serialization of a Javascript object.
既然你能做json.success
,你就没有“JSON 数据”,你有一个 Javascript 对象。JSON 或 JavaScript Object Notation 只不过是 Javascript 对象的序列化。
As other answers have stated, you can use Object.keys()
to list the fields of an object.
正如其他答案所述,您可以使用Object.keys()
来列出对象的字段。
回答by arjabbar
Object.keys()
can be called on any JavaScript object to get back a list of keys.
Object.keys()
可以在任何 JavaScript 对象上调用以获取键列表。