无法使用“-"访问 JSON 属性;短跑 [英] Unable to access JSON property with "-" dash

查看:31
本文介绍了无法使用“-"访问 JSON 属性;短跑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当字符串包含破折号时,我无法从 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).

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"]

这篇关于无法使用“-"访问 JSON 属性;短跑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆