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

发布于 2025-02-10 15:57:20 字数 307 浏览 3 评论 0原文

当字符串具有仪表板字符时,我无法从json对象检索值:

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

如果我尝试引用解析jsonobj.profile-id它返回reference> reference> referenceerror:“ id”不是定义但是jsonobj.user_id将返回6789

我没有办法修改外部API调用返回的值,并试图解析返回的字符串以删除破折号会破坏url urls等。也通过。帮助?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

微凉徒眸意 2025-02-17 15:57:20

jsonobj.profile -id是一种减法表达式(即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"]
孤千羽 2025-02-17 15:57:20

此答案,请注意,在node.js中,如果您使用数组语法[] 所有嵌套的JSON键都应遵循该语法

这是错误的方法

json.first.second.third['comment']

,并将给您“未定义”错误。

这是正确的方法

json['first']['second']['third']['comment'] 

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

This is the wrong way

json.first.second.third['comment']

And will give you the 'undefined' error.

This is the correct way

json['first']['second']['third']['comment'] 
橘味果▽酱 2025-02-17 15:57:20

对于Ansible和使用连字符,这对我有用:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]

For ansible, and using hyphen, this worked for me:

    - name: free-ud-ssd-space-in-percent
      debug:
        var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
殤城〤 2025-02-17 15:57:20

如果您在Linux中,请尝试使用以下模板打印包含破折号的JSON值,

jq '.["value-with-dash"]'

它对我有用。

If you are in Linux, try using the following template to print JSON value which contains dashes '-'

jq '.["value-with-dash"]'

It worked for me.

愛放△進行李 2025-02-17 15:57:20

对于任何试图将可接受的解决方案应用于荷抗价值模板的人,如果您要嵌套双打,则必须使用单个报价:

value_template: "{{ value_json['internet-computer'].usd }}"

For anyone trying to apply the accepted solution to HomeAssistant value templates, you must use single quotes if you are nesting in doubles:

value_template: "{{ value_json['internet-computer'].usd }}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文