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?
We can have duplicate keys in a JSON object, and it would still be valid.
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".
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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.
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]);
You mean something like this?
keys = Object.keys(json_object) key_to_use = keys[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With