4

I have a json in the following format:

{
 "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.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
XVirtusX
  • 679
  • 3
  • 11
  • 30

4 Answers4

7

Object.keys()

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));
epascarello
  • 204,599
  • 20
  • 195
  • 236
3

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+.

gfpacheco
  • 2,831
  • 2
  • 33
  • 50
1

A simple loop will work. Iterate over all the indices. If you want to get the content use 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);
}
depperm
  • 10,606
  • 4
  • 43
  • 67
1

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)
    }
}
ralh
  • 2,514
  • 1
  • 13
  • 19
  • Alreay tried that. But I only get one letter of the entire json in each loop. First iteration outputs "{", second iteration outputs ' " ' third outputs "n" and so on... – XVirtusX Jul 31 '15 at 13:39
  • Is `object` a JSON - a string representing a JS object - or a proper JS object? If it's a JSON, you need to do `JSON.parse(yourJSONHere)`. – ralh Jul 31 '15 at 13:41