3

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
  • 128,537
  • 12
  • 134
  • 188
XVirtusX
  • 639
  • 3
  • 11
  • 28

4 Answers4

5

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
  • 195,511
  • 20
  • 184
  • 225
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,655
  • 2
  • 33
  • 46
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
  • 9,662
  • 4
  • 42
  • 64
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,394
  • 1
  • 11
  • 18
  • 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