Search code examples
javascriptphparraysjsonsteam-web-api

How to decode multidimensional JSON from external url in JS?


I am using this API:

http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json

I want to search this API for name based on its id.

In PHP it would look like this:

$id = 730; // input ID

$url = 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json';

$content = file_get_contents($url) ;
$data = json_decode($content, true);

$key = array_search($id, array_column($data['applist']['apps'], 'appid'));

echo $data['applist']['apps'][$key]['name'] // returns Counter-Strike: Global Offensive

Is it possible to replicate this process in JS? Or am I better off creating a second PHP file and accessing it with AJAX?


Solution

  • Sure, you can see the answer of this question: Get JavaScript object from array of objects by value of property

    But i think you'll have cross-origin issues if you do it in browser:

    Access to XMLHttpRequest at 'http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json' 
    has been blocked by CORS policy: 
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    

    This steam API is blocking access from js in browser.