Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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