Search code examples
htmljsonfetch

How to extract data obtained as JSON from API request into an HTML table


When utilizing the following script, I can see through the Chrome Dev Tool console that the API returns an assortment of sections such as object, orbit, phys_param, signature, and proto. I want to take the data provided in the object, orbit, and phys_param sections and extrapolate them into an HTML table. On this table, I would like to have a subset of specific data from these sections. As an example, I would like to make a table that has the fullname variable that is present on the object section, the mean motion variable that is present on the orbit section, and the diameter variable in the phys_param section. I also noticed that some of the data is inside a key-value list which itself is an element of another list. How can I access these specific data section within the returned lists?

fetch('https://ssd-api.jpl.nasa.gov/sbdb.api?spk=2000001&phys-par=1')

.then(response => response.json()) .

then(data => { console.log(data) })

Solution

  • You can use the "prettify" version of JSON.stringify() as in

    JSON.stringify(d,null,2)
    

    to create a human readable version of the data. Then you can build the table like this:

    // CORS policy currently prevents direct access to the resource. obj contains a possible result: 
    const obj={"orbit":{"condition_code":"0","first_obs":"1995-01-05","data_arc":"9520","rms":"0.43","not_valid_before":null,"t_jup":"3.310","last_obs":"2021-01-28","source":"JPL","moid_jup":"2.09","producer":"Davide Farnocchia","soln_date":"2021-04-13 11:04:44","elements":[{"sigma":"4.8e-12","units":null,"label":"e","name":"e","title":"eccentricity","value":"0.0789"},{"label":"a","units":"au","sigma":"1e-11","title":"semi-major axis","name":"a","value":"2.77"},{"label":"q","sigma":"1.9e-11","units":"au","title":"perihelion distance","name":"q","value":"2.55"},{"label":"i","units":"deg","sigma":"4.6e-09","title":"inclination; angle with respect to x-y ecliptic plane","name":"i","value":"10.6"},{"name":"om","title":"longitude of the ascending node","sigma":"6.2e-08","units":"deg","label":"node","value":"80.3"},{"label":"peri","units":"deg","sigma":"6.6e-08","title":"argument of perihelion","name":"w","value":"73.4"},{"title":"mean anomaly","name":"ma","label":"M","sigma":"6.6e-09","units":"deg","value":"60.1"},{"value":"2459919.898","title":"time of perihelion passage","name":"tp","label":"tp","sigma":"3.1e-08","units":"TDB"},{"value":"1680","name":"per","title":"sidereal orbital period","sigma":"9.3e-09","units":"d","label":"period"},{"value":"0.214","sigma":"1.2e-12","units":"deg/d","label":"n","name":"n","title":"mean motion"},{"name":"ad","title":"aphelion distance","sigma":"1.1e-11","units":"au","label":"Q","value":"2.99"}],"not_valid_after":null,"n_del_obs_used":60,"orbit_id":"48","n_dop_obs_used":0,"epoch":"2460200.5","n_obs_used":1075,"cov_epoch":"2458849.5","two_body":null,"sb_used":"SB441-N373","comment":null,"pe_used":"DE441","equinox":"J2000","moid":"1.58","model_pars":[]},"signature":{"version":"1.3","source":"NASA/JPL Small-Body Database (SBDB) API"},"phys_par":[{"desc":"absolute magnitude (magnitude at 1 au from Sun and observer)","value":"3.33","name":"H","units":null,"sigma":null,"title":"absolute magnitude","ref":"MPO719049","notes":"IRAS observations used: 15"},{"title":"magnitude slope","ref":"PDS3 (MPC 17257)","notes":"Fit","name":"G","sigma":null,"units":null,"desc":"magnitude slope parameter used in the standard asteroid H/G magnitude law","value":"0.12"},{"title":"diameter","notes":null,"ref":"Nature vol. 537, pp515-517 (22 September 2016)","value":"939.4","desc":"effective body diameter","name":"diameter","units":"km","sigma":"0.2"},{"ref":"Nature vol. 537, pp515-517 (22 September 2016)","notes":"fit w.r.t. center of mass and in body-fixed frame","title":"extent","desc":"tri(or bi)-axial body dimensions","value":"964.4 x 964.2 x 891.8","sigma":"0.2 x 0.2 x 0.2","units":"km","name":"extent"},{"ref":"Nature vol. 537, pp515-517 (22 September 2016)","notes":null,"title":"GM","units":"km^3/s^2","sigma":"0.0009","name":"GM","desc":"standard gravitational parameter: product of the mass (M) and gravitational constant (G)","value":"62.6284"},{"sigma":"0.008","units":"g/cm^3","name":"density","value":"2.162","desc":"bulk density","notes":null,"ref":"Nature vol. 537, pp515-517 (22 September 2016)","title":"bulk density"},{"title":"rotation period","notes":"derived from published value: 952.1532 +/- 0.0001 deg./day","ref":"Nature vol. 537, pp515-517 (22 September 2016)","value":"9.074170","desc":"body rotation period (synodic)","name":"rot_per","units":"h","sigma":"0.000001"},{"name":"pole","units":null,"sigma":"0.007/0.002","value":"291.421/66.758","desc":"spin-pole direction in R.A./Dec.","title":"pole direction","notes":null,"ref":"Nature vol. 537, pp515-517 (22 September 2016)"},{"ref":"Li et al. (2006) Icarus v182:pp143-160","notes":"V-band geometric albedo","title":"geometric albedo","sigma":"0.003","units":null,"name":"albedo","desc":"geometric albedo","value":"0.090"},{"name":"BV","units":null,"sigma":"0.014","desc":"color index B-V magnitude difference","value":"0.713","title":"B-V","ref":"EAR-A-5-DDR-UBV-MEAN-VALUES-V1.2","notes":"#obs=52; phase (min.=1.47, mean=11.85, max.=22.59) deg."},{"name":"UB","units":null,"sigma":"0.026","desc":"color index U-B magnitude difference","value":"0.426","title":"U-B","ref":"EAR-A-5-DDR-UBV-MEAN-VALUES-V1.2","notes":"#obs=52; phase (min.=1.47, mean=12.16, max.=22.59) deg."},{"value":"G","desc":"Tholen spectral taxonomic classification","units":null,"sigma":null,"name":"spec_T","notes":"used 7 color indices; used ground-based radiometric albedo","ref":"EAR-A-5-DDR-TAXONOMY-V4.0","title":"Tholen spectral type"},{"desc":"SMASSII spectral taxonomic classification","value":"C","units":null,"sigma":null,"name":"spec_B","ref":"EAR-A-5-DDR-TAXONOMY-V4.0","notes":"based on a high-resolution spectrum by Xu et al. (1995) or Bus and Binzel (2002)","title":"SMASSII spectral type"}],"object":{"prefix":null,"orbit_class":{"name":"Main-belt Asteroid","code":"MBA"},"orbit_id":"48","shortname":"1 Ceres","fullname":"1 Ceres (A801 AA)","neo":false,"pha":false,"spkid":"20000001","kind":"an","des":"1"}};
    // original URL: 'https://ssd-api.jpl.nasa.gov/sbdb.api?spk=2000001&phys-par=1'
    fetch('https://dummyjson.com/users')
    .then(response =>response.json()).then(d =>{
     d=obj;  // (CORS fix)
     d.d={}; // add a property `d` as a sub-object with addressable names:
     d.phys_par.concat(d.orbit.elements).forEach(e=>
       d.d[e.title.replaceAll(" ","")]=[e.title,e.value,e.sigma,e.units]);
     
     document.querySelector("#out").innerHTML=
      "<h2>"+d.object.fullname+"</h2>"
     +"<table><tr><th></th><th>value</th><th>sigma</th><th>units</th></tr>"
     +Object.values(d.d).map(arr=>`<tr><td>${arr.join("</td><td>")}</td></tr>`).join("\n")
     +"</table>"
     
     // + JSON.stringify(d,null,2) // uncomment this line to show whole data structure ...
    });
    #out {white-space:pre;}
    th   {text-align: left; }
    <div id="out"></div>