Javascript - 读取格式为url的JSON字段

问题描述 投票:1回答:1

REST API将JSON作为字段发回给我。

如何使用Javascript阅读这些字段?这不起作用......

var json = JSON.parse(profile);

console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]); 

错误:

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at Strategy._verify (D:\Development\NodeJS\EID_TEST_NODEJS\server.js:33:21)
at validateCallback (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\strategy.js:61:14)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\passport-saml\lib\passport-saml\saml.js:845:5
at _fulfilled (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:854:54)
at self.promiseDispatch.done (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:883:30)
at Promise.promise.promiseDispatch (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:816:13)
at D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:624:44
at runSingle (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:137:13)
at flush (D:\Development\NodeJS\EID_TEST_NODEJS\node_modules\q\q.js:125:13)

JSON从api发回:

{
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511",  
etc....
}

问题解决了!谢谢@Mike

更改此代码:

var json = JSON.parse(profile);
console.log(json["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]); 

对于这段代码:

console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]);

谢谢您的帮助!

javascript json rest
1个回答
0
投票

观察:

你正试图解析JSON Object。无需再次解析JSON对象,因为在从API发回时已经解析了JSON对象。

enter image description here

工作演示

var profile = {
"issuer":"www.econtract.be",
"nameID":"00081007501",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality":"Hasselt",
"be:fedict:eid:idp:card-validity:end":"2023-03-03T00:00:00Z",
"be:fedict:eid:idp:card-number":"592548451825",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier":"00081007501",
"be:fedict:eid:idp:nationality":"Belg",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/dateofbirth":"2000-08-10T00:00:00Z",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/gender":"1",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/postalcode":"3511"
};

console.log(profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/locality"]); 
© www.soinside.com 2019 - 2024. All rights reserved.