-1

I'm parsing an API in NodeJS that returns this data, as a string:

{
    "query": {
        "count": 1,
        "created": "2013-12-09T08:05:21Z",
        "lang": "en-US",
        "results": {
            "rate": {
                "id": "GBPEUR",
                "Name": "GBP to EUR",
                "Rate": "1.1938",
                "Date": "12/9/2013",
                "Time": "3:05am",
                "Ask": "1.194",
                "Bid": "1.1936"
            }
        }
    }

}

I'd like to convert this into a javascript Object so that I can parse it like var rate = obj.query.results.rate.Rate.

I've tried using Node's QueryString Parse() but this doesn't work as expected, and eval() doesn't work either. How can I achieve this (obviously preferably without using eval())?

JVG
  • 20,198
  • 47
  • 132
  • 210

1 Answers1

2

You'd use JSON.parse

JSON.parse(json_string)
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    That assumes that the String is a **valid** JSON. Which may or may not be the case. Wouldn't some sanitation be advisable? – ZenMaster Dec 09 '13 at 08:21
  • The posted data is valid JSON, I already linted it before answering – adeneo Dec 09 '13 at 08:22
  • I know that the example data is a valid JSON, I am saying that it may not be in all cases, depending on which API of which Node module is being called. For all you know - it's a string that kinda looks like an object. Basically - that there is a bug and one would be wise to do some defensive programming (if that is at all possible). Just trying to add something to an already fine answer. – ZenMaster Dec 09 '13 at 08:23
  • In that case JSON.parse just fails. If you're expecting JSON, there's no need to write something fancy to see if it's JSON – adeneo Dec 09 '13 at 08:24
  • Personally I'd use domains if it was an issue, but it rarely is. – adeneo Dec 09 '13 at 08:25