【问题标题】:Read property from a Json object in typescript/javascript从 typescript/javascript 中的 Json 对象读取属性
【发布时间】:2019-12-06 02:51:08
【问题描述】:

我正在使用从第三方 API 收到的身份验证令牌。我在下面给出了一个解码令牌的样本,

{
    "nbf": 1564128888,
    "exp": 1564132488,
    "iss": "http://example.com:5002",
    "aud": "http://example.com:5002/resources",

    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com",
    "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse",    
    "amr": ["custom"]
}

我正在努力阅读 javascript 中的“名称”声明。如何在 javascript 或 typescript 中读取该属性?

【问题讨论】:

  • 您能澄清一下您要阅读的内容吗?是不是你需要找到任何以/claims/name 结尾的键并用它们的值做一些事情?
  • 名称键是动态的吗?
  • @AsafAviv 你这是什么意思?
  • @GenericUser 是的,我是。尝试读取名称并对其进行处理。
  • nvm 查看 Philip 的回答

标签: javascript typescript auth-token


【解决方案1】:

您可以像这样访问复杂的属性名称:

const name = token["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]

您也可以将其抽象出来以实现可重用性 (like the ClaimTypes in C#)

const ClaimTypes = {
  name: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
  // other relevant claims
};

const name = token[ClaimTypes.name];

【讨论】:

    【解决方案2】:

    JSON.parse(yourData) - 将 JSON 转换为 JS JSON.stringify(yourData) - 从 JS 到 JSON

    所以在 JSON.parse 之后你会得到 JS 对象并且能够得到你的Data.name

    在这里您可以阅读: 医疗器械网络: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    你可以试试例如:https://jsonformatter.org/json-parser

    【讨论】:

      【解决方案3】:

      您将以字符串的形式获取数据,将其转换为 json

      let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
      let parsedJSON = JSON.parse(jsonData)
      console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"]) // Micky Mouse
      console.log(parsedJSON["nbf"]) // 1564128888
      console.log(parsedJSON["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]) // Micky@gmail.com

      然后像parsedJSON["your key"] 一样阅读它。左侧的东西是属性名称或键。您可以通过

      检索它们

      let jsonData = '{"nbf": 1564128888,"exp": 1564132488,"iss": "http://example.com:5002","aud": "http://example.com:5002/resources","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "Micky@gmail.com","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "Micky Mouse","amr": ["custom"]}'
      let parsedJSON = JSON.parse(jsonData)
      console.log(Object.keys(parsedJSON))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 1970-01-01
        • 2011-01-16
        • 2011-08-16
        • 2023-03-29
        • 2020-04-08
        相关资源
        最近更新 更多