Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

APIs

Eitan Peles
Eitan Peles
4,453 Points

How can I retrieve objects from a JSON API which cointains spaces?

I'm using JS in order to obtain the currency from a JSON API, but its objects contains spaces and I cannot access them.

{ "Realtime Currency Exchange Rate": { "1. From_Currency Code": "brl", "2. From_Currency Name": null, "3. To_Currency Code": "ils", "4. To_Currency Name": null, "5. Exchange Rate": "0.95077386", "6. Last Refreshed": "2018-08-14 12:25:28", "7. Time Zone": "UTC" } }

This is how I'm trying to get the objects:

printStock(stock["Realtime Currency Exchange Rate"]["1. From_Currency Code"], stock["Realtime Currency Exchange Rate"]["3. To_Currency Code"], stock["Realtime Currency Exchange Rate"]["5. Exchange Rate"]);

Rebecca Jensen
Rebecca Jensen
11,580 Points

Hmm. I tried it in a repl.it and was able to access it just the way you have here.

let stock = { "Realtime Currency Exchange Rate": 
  { 
    "1. From_Currency Code": "brl", 
    "2. From_Currency Name": null, 
    "3. To_Currency Code": "ils", 
    "4. To_Currency Name": null, 
    "5. Exchange Rate": "0.95077386", 
    "6. Last Refreshed": "2018-08-14 12:25:28", 
    "7. Time Zone": "UTC" 
  } 
}

console.log(stock["Realtime Currency Exchange Rate"]["1. From_Currency Code"], stock["Realtime Currency Exchange Rate"]["3. To_Currency Code"], stock["Realtime Currency Exchange Rate"]["5. Exchange Rate"]);

//logs:
// brl ils 0.95077386

The problem could be outside the scope of what you've shared here.

1 Answer

I was able to get it in php laravel framework, but the code can also work in php core. just change the dd to console.write() or echo or equivalent of that.

$json = json_decode($data, true);
dd($json["Realtime Currency Exchange Rate"]["1. From_Currency Code"]);