Home > Web Front-end > JS Tutorial > How Do I Access JSON Properties Containing Hyphens in JavaScript?

How Do I Access JSON Properties Containing Hyphens in JavaScript?

Patricia Arquette
Release: 2024-11-25 00:10:12
Original
138 people have browsed it

How Do I Access JSON Properties Containing Hyphens in JavaScript?

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
}
Copy after login

Attempting to access the jsonObj.profile-id property results in the following error:

ReferenceError: "id" is not defined
Copy after login

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"]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template