2016-07-01 13 views
0

下面我有一些代碼來變換獲取JSON字符串成,取下牙套,它解析爲一個地圖變量:我是否將地圖變量正確設置爲提取的json?

let result = ''; 
let map = []; 

fetch(link) 
    .then(function(response) { 
    return response.json(); 
    }).then(function(json) { 
    result = JSON.stringify(json); //json here is like [{'a':1,'a2':2},{'b':11,'b2':12}] 
    result = result.substring(1, result.length - 1); 
    map = JSON.parse(result); 
    }).catch(function(ex) { 
    console.log('parsing failed', ex); 
    }); 

我試圖簡單地設置map=json但都給出了同樣的錯誤我有地圖重複的鍵。

如果我硬編碼我的map變量可以說[{'id':1,code: 007},{'id':2, code:014}]它的作品。我已經嘗試將result更改爲字符串並將其完全作爲示例登錄。換句話說,設置map=json應該首先工作。

我想我可能會錯過一些東西。它是什麼?

編輯#1

fetch(link) 
.then(function(response) { 
    return response.json(); 
}).then(function(json) { 
    setData(json); 
    document.getElementById("result").innerHTML = json; 
}).catch(function(ex) { 
    console.log('parsing failed', ex); 
}); 


function setData(json) { 
    map = json; 
} 

我試過,只是沒有response ok部分由Naomik給出的解決方案。 我仍然收到與map = json相同的錯誤。任何幫助?

+0

是什麼在'json'參數第二'。那麼()'包含哪些內容?它不是一個字符串嗎?如果將方括號從[['a':1,'a2':2},{'b':11,'b2':12}]'中刪除,順便說一句,您可以使用'.slice (1,-1)',你最終會得到一些無效的JSON。 – nnnnnn

+0

你正在做同樣的事情,你只是將'map = ...'移到另一個函數。您將**從不**能夠訪問回調鏈之外的數據*。閱讀[「我如何返回來自異步調用的響應?」](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)和[「爲什麼我的變量沒有改變後,我修改它的功能?」](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside功能異步) – naomik

+0

這些問題有數百個upvotes,因爲它們非常常見。瞭解異步編程是一個艱難的攀登,但一旦掌握了它,這很容易。 – naomik

回答

3

您不能在異步處理程序中設置類似這樣的變量,並期望將其設置在處理程序之外。更多關於這裏:"How do I return the response from an asynchronous call?"

我剛剛標記爲一個的重複你的問題,但有一個與你的代碼的其他問題,所以我要去的地址現在那些

在你的第二個電話.then,您正在嘗試處理json但你錯誤地做

// Why exactly are you re-stringifying the data we just parsed ? 
result = JSON.stringify(json); 

// ... wtf ? 
result = result.substring(1, result.length - 1); 

// Same as above, any vars you set here cannot be read outside of the callback. 
// This won't work like you expect (see the related question I linked above) 
map = JSON.parse(result); 

記住,JSON只是一個表示您的數據,沒有別的

  • JSON.parse將採取json 字符串並將其變成數據。
  • JSON.stringify將採取數據並將其變成json字符串。

這個例子可以幫助你有點

fetch(link).then(function(response) { 
    if (response.ok) 
    // read JSON response and parse it 
    return response.json() 
    else 
    // response is not OK, throw error 
    throw Error(response.status + " " + response.statusText) 
}) 
.then(function(data) { 
    console.log("Your data has arrived!") 
    console.log("Do something here with your data") 
    doSomething(data) 
}) 
.catch(function(err) { 
    console.error(err.message) 
}) 

function doSomething(data) { 
    console.log("Here's your data:", data); 
} 
+0

僅供參考,OP使用https://github.com/github/fetch,它已經完成了所有的解析。在github頁面上提供的示例中,命名是不幸的。 – Tomalak

+0

@Tomalak啊謝謝。因此,只需取出'.then(json => JSON.parse(json)'並直接跳到'.then(data => ...)''' – naomik

+0

是的,請參閱:https:// github。 com/github/fetch#json – Tomalak