简体   繁体   English

如何将 API 结果重新格式化为字典然后使用该字典?

[英]How can I reformat API results into a dictionary then use that dictionary?

I have an assignment where I need to key an API using a key that cannot be used by default.我有一个任务,我需要使用默认情况下无法使用的密钥来键入 API。 Currently, I'm using getJSON to pull data from an API as seen in the code below:目前,我正在使用 getJSON 从 API 中提取数据,如下面的代码所示:

$(document).ready(function() {
    $.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=DEMO_KEY", function(data){
        console.log(data);
    });
});

This makes sense, but I'm stuck from here.这是有道理的,但我被困在这里。 Essentially, I'd like to reformat the API results and store them in a dictionary so I can key the results using "sol".本质上,我想重新格式化 API 结果并将它们存储在字典中,以便我可以使用“sol”键入结果。 Ideally, the dictionary would only contain the key "sol", its value, and the key "cameras", and its values for every section within photos as seen in the API.理想情况下,字典将只包含键“sol”、它的值和键“cameras”,以及它在照片中每个部分的值,如 API 中所示。

Additionally, how would you then go about keying the dictionary using a sol value, and returning the cameras associated with that sol value?此外,您 go 如何使用 sol 值键入字典,并返回与该 sol 值关联的相机?

EDIT: The code below works great, but I'm not seeing what I would need to put after everything to use camera globally.编辑:下面的代码效果很好,但我没有看到在全局使用相机后需要添加什么。

        let new_dict = { "sol": {}, "cameras": {} };
        
        $(document).ready(function(){
            $.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=0L4UJKm4YYvddR1QdZdCihRwQIqKBGrPErgFqUsw", function(data){
                let photos = data["photo_manifest"]["photos"];
                let sol_arr = [];

                for(x in photos){
                    let photo = photos[x];
                    let sol = photo.sol;
                    let cameras = photo.cameras;

                    sol_arr.push(sol);
                    new_dict["cameras"][sol] = cameras;
                }
                new_dict["sol"] = sol_arr;
                
                let sol_value = 1;
                let camera = new_dict["cameras"][sol_value];
            });
        });
$.getJSON("https://api.nasa.gov/mars-photos/api/v1/manifests/curiosity?api_key=DEMO_KEY", function(data){
    
    let photos = data["photo_manifest"]["photos"];



    let new_dict = { "sol" : {}, "cameras": {} };

    let sol_arr = [];

    for(x in photos){
 
        let photo = photos[x];

        let sol = photo.sol;
        let cameras = photo.cameras;

        sol_arr.push(sol);
        new_dict["cameras"][sol] = cameras;
        
    }

    new_dict["sol"] = sol_arr;

});

for keying the dictionary using a sol value, you just need to put sol value like要使用 sol 值键入字典,您只需要将 sol 值放入

let sol_value = 1;
console.log(new_dict["cameras"][sol_value]); //this contains the cameras with the sol value 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM