Home > Net >  :: jQuery :: Get jSON data keys and values and display in html format
:: jQuery :: Get jSON data keys and values and display in html format

Time:10-06

How can I get data & keys from dynamic JSON file and display in table format as HTML

PS: This JSON will be dynamic and data may not be the same all the time. Eg: Some times, it will 2 sets or 3 sets of data, keys and values will be different etc...

I am trying to get the JSON from enter image description here

Results should be in below format (key - value):

<div >
  <span >id<span> - <span >1<span>
  <span >img</span> - <span >https://amp.dev/static/samples/img/product1_640x426.jpg</span>
  <span >name</span> - <span >Apple</span>
  <span >price</span> - <span >1.99</span>
  <span >stars</span> - <span >&#9733;&#9733;</span>
  <span >attribution<span> - <span >visualhunt</span>
  <span >url</span> - <span >#</span>
  <span >color</span> - <span >green</span>
<div>

<div >
  <span >id</span> - <span >1</span>
  <span >img</span> - <span >https://amp.dev/static/samples/img/product1_640x426.jpg</span>
  <span >name</span> - <span >Apple</span>
  <span >price</span> - <span >1.99</span>
  <span >stars</span> - <span >&#9733;&#9733;</span>
  <span >attribution</span> - <span >visualhunt</span>
  <span >url</span> - <span >#</span>
  <span >color</span> - <span >green</span>
<div>

etc...

CodePudding user response:

You can use foreach to display all keys and values like this::

array.foreach((value, index) => { enter code hereBy Index you can display allenter code here enteries of array by value you can display all values such as value.name })

CodePudding user response:

Below trick has done for this

jsFiddle

var atd, atr, temp;
fetch('https://amp.gmail.dev/playground/public/ssr_amp_list')
    .then((response) => response.json())
    .then((data) => {
    data.items.map(myList => {
        var __keys = Object.keys(myList); 
        var __values = Object.values(myList);

        $.each(__values, function(index,myList) {
            if (myList.includes('https:')) {
                myList = '<img src="' myList '" width="30">'             
            }

            atd = '<td>' myList '</td>'
            atr  = atd;
            if((__keys.length) -1 == index){
                temp =  '<tr>' atr '</tr>'
                atr = '';
            }
        })

    });
    $('#data table').html(temp) 
})
  • Related