Accessing JSON Properties with Dash Characters
When retrieving values from a JSON object, it's important to note that accessing properties with hyphenated names can lead to errors. For instance, consider the following JSON object:
{ "profile-id":1234, "user_id":6789 }
Attempting to access the jsonObj.profile-id property results in the following error:
ReferenceError: "id" is not defined
This issue arises because the "-" character in the property name is not allowed in JavaScript identifiers. To resolve this, you can access the property using brackets:
jsonObj["profile-id"]
This approach correctly retrieves the value of the "profile-id" property, which is 1234 in this case. By enclosing the property name in brackets, you allow JavaScript to properly interpret it as a string, regardless of any special characters it may contain.
The above is the detailed content of How Do I Access JSON Properties Containing Hyphens in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!