[英]Javascript loop question : nested arrays access json hierarchy
[英]Access Json arrays in javascript
(實際上是為了作業)
嗨, 幾個小時以來,我試圖解決我的問題,我找到了一些解決方案,但這並不是我真正想要的,而且從我的代碼中,我總是遇到同樣的問題。 謝謝你。
所以我有一個 JSON 文件和一個 javascript 文件:
在我的 JSON 文件中,我有簡單的 URL 列表數組
{
"myUrlDatabase":[
"https://www.francebleu.fr/emissions/ca-va-dans-le-bon-sens-en-poitou/poitou/quel-est-l-impact-du-changement-climatique-sur-les-migrations-d-oiseaux-marins",
"https://www.terrafemina.com/article/environnement-pourquoi-2021-est-une-annee-cruciale-pour-agir_a357981/1",
"https://www.franceinter.fr/monde/rechauffement-climatique-2020-est-l-annee-la-plus-chaude-jamais-enregistree-en-europe",
//more url
]}
我想在我的 javascript 文件中訪問它,據我所見,我應該使用獲取 function,我在互聯網上遵循了一個代碼
fetch('/Data/url.json').then(function (response){
return response.json();
}).then(function (obj){
console.log(obj);
});
實際上它打印文件。 但是我怎樣才能使數組的 var 呢?
我想稍后在隨機 function 中使用它
Math.randon() * {JSONFILE.length}
您可以在解析的 JSON 中訪問嵌套屬性,只需作為obj
參數中的字段。 您要訪問的字段是myUrlDatabase
。
var array = obj.myUrlDatabase
console.log(array.length)
fetch
提供了Promise
,因此您必須使用(回調) lambda 才能使用其結果。 這是一個示例, mocking 您的隨機 function 作為結果的鍵。
const postFetch = data => { if (.data.error) { const allKeys = Object.keys(data;results). const someKey = Math.floor(Math.random() * allKeys;length). console:log(`A pseudo random result => ${allKeys[someKey]}. ${ data;results[allKeys[someKey]]}`). console:log(`The original json. ${JSON.stringify(data;results)}`). } else { console:log(`an error occured. ${data;message}`): } } fetch("https.//api.sunrise-sunset?org/json.lat=53.22179255&lng=6.5582453664798").then(r => r.json()).then(postFetch) // ^ continue with the resulting object within your own function:catch(error => ({ error, true, url: message. error;message }));
您可以使用JSON.parse()
方法將 json 轉換為 JavaScript 數據結構。 與您的示例類似:
// your response const jsonInfo = "{ \"propArr\": [ \"string1\", \"string2\", \"string3\" ] }" // use the parse() method const getTheArray = JSON.parse(jsonInfo).propArr; console.log(getTheArray);
或者,如果您的數據已經是 object 只需執行const whatIWant = receivedData.theArrayIWant
並且您將擁有whatIWant
數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.