2013-11-26 82 views
0

我看了Yahoo! Messenger API文档中,看我怎样才能访问令牌,我发现这一点:Yahoo!什么样的数据? Messenger API返回请求?

调用看起来是这样的:

https://login.yahoo.com/WSLogin/V1/get_auth_token?&login=username&passwd=mypassword&oauth_consumer_key=consumerkey

此调用的结果是单个值,所述RequestToken

RequestToken=jUO3Qolu3AYGU1KtB9vUbxlnzfIiFRLP...

然后将此令牌用于第二个请求,该请求将PART部分交换为OAuth访问令牌。你可以在这里找到更多关于获取访问令牌的标准方法的信息。

我想结果是标准结果,但我不知道这是什么样的数据。我的意思是它不是XML或JSON。

我想这样的字符串转换成JSON:

{ 
    RequestToken: "jU0..." 
} 

有什么标准转换器/分析器或我必须建立一个?


此外,另一个请求可以看起来象下面这样:

Error=MissingParameters 
ErrorDescription=Sorry, try again with all the required parameters. 

,我想将其转换成JSON:

{ 
    Error: "MissingParameters", 
    ErrorDescription: "Sorry, try again with all the required parameters." 
} 

这将是很容易建立这样的解析器,但我不想重新发明轮子。

回答

0

我决定写我自己的功能。如果有一个标准的算法来解析这样的字符串留下评论。

/* 
* Transform a string like this: 
* 
* "Field1=123 
* Field2=1234 
* Field3=5" 
* 
* into an object like this: 
* 
* { 
*  "Field1": "123", 
*  "Field2": "1234", 
*  "Field3": "5", 
* } 
* 
* */ 
function parseResponse (str) { 

    // validate the provided value 
    if (typeof str !== "string") { 
     throw new Error("Please provide a string as argument: " + 
               JSON.stringify(str)); 
    } 

    // split it into lines 
    var lines = str.trim().split("\n"); 

    // create the object that will be returned 
    var parsedObject = {}; 

    // for every line 
    for (var i = 0; i < lines.length; ++i) { 
     // split the line 
     var splits = lines[i].split("=") 
      // and get the field 
      , field = splits[0] 
      // and the value 
      , value = splits[1]; 

     // finally set them in the parsed object 
     parsedObject[field] = value; 
    } 

    // return the parsed object 
    return parsedObject; 
};