Javascript 无法使用“-”破折号访问 JSON 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13869627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to access JSON property with "-" dash
提问by user1902467
I am unable to retrieve a value from a json object when the string has a dash character:
当字符串有破折号时,我无法从 json 对象中检索值:
{
"profile-id":1234, "user_id":6789
}
If I try to reference the parsed jsonObj.profile-idit returns ReferenceError: "id" is not definedbut jsonObj.user_id will return 6789
如果我尝试引用解析的jsonObj.profile-id它返回ReferenceError: "id" is not defined但 jsonObj.user_id 将返回 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?
我没有办法修改外部 api 调用返回的值,并尝试解析返回的字符串以删除破折号会破坏 url 等,这些也是传递的。帮助?
回答by SLaks
jsonObj.profile-idis a subtraction expression (i.e. jsonObj.profile - id).
jsonObj.profile-id是减法表达式(即jsonObj.profile - id)。
To access a key that contains characters that cannot appear in an identifier, use brackets:
要访问包含不能出现在标识符中的字符的键,请使用方括号:
jsonObj["profile-id"]
回答by t.vdh
For ansible, and using hyphen, this worked for me:
对于ansible,并使用连字符,这对我有用:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
回答by Sohel Ahmed Mesaniya
In addition to this answer, note that in Node.js if you access JSON with the array syntax []all nested JSON keys should follow that syntax
除了这个答案,请注意,在 Node.js 中,如果您使用数组语法访问 JSON,则[]所有嵌套的 JSON 键都应遵循该语法
This is the wrong way
这是错误的方法
json.first.second.third['comment']
and will will give you the 'undefined' error.
并且会给你“未定义”错误。
This is the correct way
这是正确的方法
json['first']['second']['third']['comment']

