2017-04-10 62 views
1

我知道這個問題會以不同的方式被問到,但我正在努力圍繞如何處理從API URI返回的數據,希望更清楚地瞭解如何正確使用它。如何使用純JavaScript從API解析JSON?

我練的API,並決定做一個簡單的天氣應用程序,從openweathermap.com

獲取數據的一個例子URI是http://api.openweathermap.org/data/2.5/weather?q=Los+Angeles&APPID=myApiKey

我用我的網頁上,在任何填充輸入Concat的這個數據輸入城市或郵政編碼,然後打印完整路徑作爲鏈接工作得很好。但是,當我嘗試從這個URI解析數據,我得到

Uncaught SyntaxError: Unexpected token h in JSON at position 0 
    at JSON.parse (<anonymous>) 
    at getWeather (index.js:25) 
    at HTMLButtonElement.onclick 

我試圖打破這個數據API的數據裏面,所以我可以適當地顯示像溫度,風,溼度等

事情錯誤

這是我寫的測試代碼,如果我正確地獲取數據。

// Set API variables 
const api = "http://api.openweathermap.org/data/2.5/weather?q="; 
const apiKey ="myAPIKey"; 

// Set City and Units 
let unitType = "imperial"; 
let units = "&units=" + unitType; 

function setup() { 
    var button = document.getElementById('submit'); 
    button.click = getWeather(); 
} 


function getWeather() { 
    let city = document.getElementById('city').value; 
    let fullPath = api + city + "&APPID=" + apiKey + units; 

    console.log(city); 
    //document.getElementById('weatherData').innerHTML='<a href="' + fullPath + '">' + city + '</a>'; 

    let data = fullPath; 
    let obj = JSON.parse(data); 
    document.getElementById('weatherData').innerHTML = obj.main.temp; 
} 

當你點擊提交,看起來像在頁面上按鈕的getWeather()函數被調用:

<!doctype html> 
<html> 
    <head></head> 
    <body> 
    <input type="text" id="city" placeholder="Enter a city" /> 
    <button onclick="getWeather()" id="submit">Submit</button> 
    <div id="weatherData" style="background: #ccc; padding: 20px; margin-top: 25px;"> 
    </div> 


    <script src="index.js"></script> 
    </body> 
</html> 

我在做什麼錯?我從來沒有使用過API,所以請原諒我,如果我在這裏看起來很無知。當我讓程序在它的屏幕上打印連接的URL(鏈接到URI本身)時,但現在我試圖實際提取數據,從上面得到錯誤。這裏

編輯是返回的API數據的例子:

{ 
    "coord": { 
    "lon": -96.81, 
    "lat": 32.78 
    }, 
    "weather": [ 
    { 
     "id": 804, 
     "main": "Clouds", 
     "description": "overcast clouds", 
     "icon": "04d" 
    } 
    ], 
    "base": "stations", 
    "main": { 
    "temp": 295.15, 
    "pressure": 1016, 
    "humidity": 78, 
    "temp_min": 294.15, 
    "temp_max": 296.15 
    }, 
    "visibility": 20921, 
    "wind": { 
    "speed": 4.1, 
    "deg": 180 
    }, 
    "clouds": { 
    "all": 100 
    }, 
    "dt": 1491835980, 
    "sys": { 
    "type": 1, 
    "id": 2596, 
    "message": 0.0099, 
    "country": "US", 
    "sunrise": 1491825755, 
    "sunset": 1491872065 
    }, 
    "id": 4684888, 
    "name": "Dallas", 
    "cod": 200 
} 
+0

帖子裏是API響應 – hindmost

+0

的例子你真的向API發出請求? – LiverpoolOwen

+0

哎呀,對不起,我打算這麼做。現在添加了。 – crescentfresh

回答

0
let fullPath = api + city + "&APPID=" + apiKey + units; // fullPath is a string representing an URL 
let data = fullPath; // data is a string representing an URL 
let obj = JSON.parse(data); // You try to parse an URL, not JSON 

您嘗試解析一個URL,所以這是行不通的。在此URL上創建XHR請求以獲取您的JSON數據。

編輯:

請求遠程JSON文件,使用fetch API(包括polyfill如果你的瀏覽器不實現獲取):

fetch('/data.json') 
    .then(function(response) { 
    return response.json(); 
}).then(function(json) { 
    console.log('parsed json', json); 
}).catch(function(ex) { 
    console.log('parsing failed', ex); 
})