繁体   English   中英

从Typescript / javascript中的Json对象读取属性

[英]Read property from a Json object in typescript/javascript

我正在使用从第三方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或打字稿中读取该属性?

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

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

您也可以将其抽象化以提高可重用性( 例如C#中的ClaimTypes

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

const name = token[ClaimTypes.name];

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

所以在JSON.parse之后,您将获得JS对象并能够获得yourData.name

在这里您可以阅读:MDN: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

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

您将以字符串形式获取数据,并将其转换为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)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM