Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON key name [duplicate]

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?

like image 792
Prince Avatar asked Jul 15 '16 13:07

Prince


People also ask

Can JSON have duplicate key?

We can have duplicate keys in a JSON object, and it would still be valid.

Can JSON have two keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Can JavaScript object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Does Yaml allow duplicate keys?

Duplicate keys in YAML files are not allowed in the spec (https://yaml.org/spec/1.2.2/#nodes, https://yaml.org/spec/1.0/#model-node), but the older version of symfony/yaml does not complain about them.


2 Answers

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]);
like image 81
gurvinder372 Avatar answered Oct 02 '22 05:10

gurvinder372


You mean something like this?

keys = Object.keys(json_object) key_to_use = keys[0]; 
like image 41
CyberBrain Avatar answered Oct 02 '22 06:10

CyberBrain