51

I have the following JSON data: {"success":"You are welcome"} that I have named json in my JavaScript code.

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?

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Prince
  • 1,190
  • 3
  • 13
  • 25

5 Answers5

99

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]);
Nicholas Smith
  • 674
  • 1
  • 13
  • 27
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
7

You mean something like this?

keys = Object.keys(json_object)
key_to_use = keys[0];
CyberBrain
  • 127
  • 3
7

Try this code

alert(Object.keys({"success":"You are welcome"})[0]);
Kalu Singh Rao
  • 1,671
  • 1
  • 16
  • 21
The Internet
  • 7,959
  • 10
  • 54
  • 89
4

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.

As other answers have stated, you can use Object.keys() to list the fields of an object.

Aaron
  • 24,009
  • 2
  • 33
  • 57
3

Object.keys() can be called on any JavaScript object to get back a list of keys.

arjabbar
  • 6,044
  • 4
  • 30
  • 46