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.

2
  • What do you mean by "print"? Commented Jul 31, 2015 at 13:21
  • You'd loop over the properties and print them...!? Commented Jul 31, 2015 at 13:21

4 Answers 4

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)); 
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

That was it man! It works on Firefox also! Many thanks!
Yes, sure! I mean it won't work on IE earlier than 9
2

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); }

1 Comment

already tried that. But it only outputs the number of keys. (0, 1, 2...)
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) } } 

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.