javascript 如何打印json属性名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31747223/
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
How to print json property name?
提问by XVirtusX
I have a json in the following format:
我有以下格式的json:
{
"nm_questionario":{"isEmpty":"MSGE1 - Nome do Questionário"},
"ds_questionario":{"isEmpty":"MSGE1 - Descrição do Questionário"},
"dt_inicio_vigencia":{"isEmpty":"MSGE1 - Data de Vigência"}
}
how can I print the names of the properties using javascript? I want to retrieve the names nm_questionario
, dt_inicio_vigencia
and ds_questionario
. Tried many things already but to no avail.
如何使用 javascript 打印属性的名称?我想检索名称nm_questionario
,dt_inicio_vigencia
和ds_questionario
. 已经尝试了很多东西,但无济于事。
回答by gfpacheco
You can get an array of the keys with var keys = Object.keys(JSON.parse(jsonString));
. Just keep in mind that it only works on IE9+.
您可以使用var keys = Object.keys(JSON.parse(jsonString));
. 请记住,它仅适用于 IE9+。
回答by epascarello
var obj = {
"nm_questionario":{"isEmpty":"MSGE1 - Nome do Questionário"},
"ds_questionario":{"isEmpty":"MSGE1 - Descrição do Questionário"},
"dt_inicio_vigencia":{"isEmpty":"MSGE1 - Data de Vigência"}
};
console.log(Object.keys(obj));
回答by depperm
A simple loop will work. Iterate over all the indices. If you want to get the content use object[index]
一个简单的循环将起作用。迭代所有索引。如果你想获得内容使用object[index]
var object={"nm_questionario":{"isEmpty":"MSGE1 - Nome do Questionário"},"ds_questionario":{"isEmpty":"MSGE1 - Descrição do Questionário"},"dt_inicio_vigencia":{"isEmpty":"MSGE1 - Data de Vigência"}};
for(var index in object) {
console.log(index);
}
回答by ralh
If you want to access the names of the properties, you can loop over them like this:
如果要访问属性的名称,可以像这样循环它们:
var object = //put your object here
for(var key in object) {
if(object.hasOwnProperty(key)) {
var property = object[key];
//do whatever you want with the property here, for example console.log(property)
}
}