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

时间:2018-03-04 15:37:48

标签: javascript json rest

REST API向我发送JSON,其中URL为字段。

如何使用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"]);

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

观察:

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

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"]);