在javascript中访问Json数组

在javascript中访问Json数组,javascript,arrays,json,Javascript,Arrays,Json,(实际上是为了一项任务) 嗨, 几个小时来,我试图解决我的问题,我找到了一些解决方案,但这并不是我真正想要的,从我的代码中,我总是遇到同样的问题。 多谢各位 我有一个JSON文件和一个javascript文件: 在我的JSON文件中,我有一个简单的URL列表数组 { "myUrlDatabase":[ "https://www.francebleu.fr/emissions/ca-va-dans-le-bon-sens

(实际上是为了一项任务)

嗨, 几个小时来,我试图解决我的问题,我找到了一些解决方案,但这并不是我真正想要的,从我的代码中,我总是遇到同样的问题。 多谢各位

我有一个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文件中访问它,根据我所看到的,我应该使用fetch函数,我在互联网上遵循了一个代码

fetch('/Data/url.json').then(function (response){
  return response.json();
}).then(function (obj){
  console.log(obj);
});
事实上,它可以打印文件。但是我怎样才能生成数组的变量呢

我想稍后在随机函数中使用它

Math.randon() * {JSONFILE.length}

您可以通过
obj
参数中的字段访问已解析JSON中的嵌套属性。要访问的字段是
myUrlDatabase

var array = obj.myUrlDatabase
console.log(array.length)

您可以通过
obj
参数中的字段访问已解析JSON中的嵌套属性。要访问的字段是
myUrlDatabase

var array = obj.myUrlDatabase
console.log(array.length)

您可以使用
JSON.parse()
方法将JSON转换为JavaScript数据结构。 与您的示例类似:

//您的回答
const jsonInfo=“{\'propArr\':[\'string1\',\'string2\',\'string3\']}”
//使用parse()方法
const getTheArray=JSON.parse(jsonInfo.propArr);

console.log(getTheArray)
您可以使用
JSON.parse()
方法将JSON转换为JavaScript数据结构。 与您的示例类似:

//您的回答
const jsonInfo=“{\'propArr\':[\'string1\',\'string2\',\'string3\']}”
//使用parse()方法
const getTheArray=JSON.parse(jsonInfo.propArr);

console.log(getTheArray)
fetch
提供了一个
承诺
,因此您必须使用(回调)lambda来使用其结果。这里有一个例子,模拟你的随机函数来获得结果的关键点

const postFetch=data=>{
如果(!data.error){
const allKeys=Object.keys(data.results);
const someKey=Math.floor(Math.random()*allKeys.length);
log(`A伪随机结果=>${allKeys[someKey]}:${
data.results[allkey[someKey]}`);
log(`原始json:${json.stringify(data.results)}`);
}否则{
log(`发生错误:${data.message}`);
}
}
取回(“https://api.sunrise-sunset.org/json?lat=53.22179255&lng=6.5582453664798")
.then(r=>r.json())
。然后(后期提取)
//^继续在您自己的函数中使用结果对象
.catch(错误=>({
错误:正确,
网址,
消息:error.message

}));
fetch
提供了一个
承诺
,因此您必须使用(回调)lambda来使用其结果。这里有一个例子,模拟你的随机函数来获得结果的关键点

const postFetch=data=>{
如果(!data.error){
const allKeys=Object.keys(data.results);
const someKey=Math.floor(Math.random()*allKeys.length);
log(`A伪随机结果=>${allKeys[someKey]}:${
data.results[allkey[someKey]}`);
log(`原始json:${json.stringify(data.results)}`);
}否则{
log(`发生错误:${data.message}`);
}
}
取回(“https://api.sunrise-sunset.org/json?lat=53.22179255&lng=6.5582453664798")
.then(r=>r.json())
。然后(后期提取)
//^继续在您自己的函数中使用结果对象
.catch(错误=>({
错误:正确,
网址,
消息:error.message
}));