1

I am working with javascript in Meteor and I make an HTTP.get request to an API and receive a response res = {..., content: "access_token=4h378fi243h085giouf245&expires=5180430", data=null}. As you can see, res.content is a string but it really represent a nice JSON object {access_token: 4h378fi243h085giouf245, expires: 5180430}.

Is there a Meteor or Javascript package/easy solution to turn that string into that object?

(I've seen some manual string parsing solutions but that seems hacky, and this seems like something Meteor or Javascript would provide for you.)

EDIT: Doing JSON.parse(res.content) is actually the first thing I tried but it gives me 'Unexpected token a', I'm guessing from 'access_token'. Why would that not work?

tscizzle
  • 11,191
  • 15
  • 54
  • 88

3 Answers3

2

It actually isn't JSON, it's a URL parameters string.

var result = {};
res.content.split("&").forEach(function(part) {
  var item = part.split("=");
  result[item[0]] = decodeURIComponent(item[1]);
});
result = JSON.parse(result);
1

All the answers here forget the fact that res.content is not JSON, but is a query string. See this question for how to get the values, with a little tweaking: How can I get query string values in JavaScript?.

I also created a JavaScript class lib called Cerealizer that parses a query string into an object. I'm sure a github search could pull up others as well.

var parser = new Cerealizer.QueryString();

res.content = parser.deserialize(res.content);
Community
  • 1
  • 1
Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
-2

JSON.parse should do what you are trying to do.

mailmindlin
  • 616
  • 2
  • 7
  • 25