无法使用“-"访问 JSON 属性短跑

2022-01-31 00:00:00 json javascript

当字符串包含破折号时,我无法从 json 对象中检索值:

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

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

如果我尝试引用已解析的 jsonObj.profile-id 它会返回 ReferenceError: "id" is not defined 但 jsonObj.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

我没有办法修改外部 api 调用返回的值,并尝试解析返回的字符串以删除破折号会破坏 URL 等,这些也是传递的.帮忙?

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?

推荐答案

jsonObj.profile-id是减法表达式(即jsonObj.profile-id).

要访问包含不能出现在标识符中的字符的键,请使用方括号:

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

jsonObj["profile-id"]

相关文章