Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

javascript - Unable to access JSON property with "-" dash

I am unable to retrieve a value from a json object when the string has a dash character:

{
"profile-id":1234, "user_id":6789
}

If I try to reference the parsed jsonObj.profile-id it returns ReferenceError: "id" is not defined but jsonObj.user_id will return 6789

I don't have a way to modify the values being returned by the external api call and trying to parse the returned string in order to remove dashes will ruin urls, etc., that are passed as well. Help?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...